diff --git a/deliverables/build.xml b/deliverables/build.xml new file mode 100644 index 0000000000000000000000000000000000000000..d3e9fedb051f87225d477294eefbedc5d43a382c --- /dev/null +++ b/deliverables/build.xml @@ -0,0 +1,73 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- You may freely edit this file. See commented blocks below for --> +<!-- some examples of how to customize the build. --> +<!-- (If you delete it and reopen the project it will be recreated.) --> +<!-- By default, only the Clean and Build commands use this build script. --> +<!-- Commands such as Run, Debug, and Test only use this build script if --> +<!-- the Compile on Save feature is turned off for the project. --> +<!-- You can turn off the Compile on Save (or Deploy on Save) setting --> +<!-- in the project's Project Properties dialog box.--> +<project name="MV3500_Deliverables" default="default" basedir="."> + <description>Builds, tests, and runs the project MV3500 Deliverables.</description> + <import file="nbproject/build-impl.xml"/> + <!-- + + There exist several targets which are by default empty and which can be + used for execution of your tasks. These targets are usually executed + before and after some main targets. They are: + + -pre-init: called before initialization of project properties + -post-init: called after initialization of project properties + -pre-compile: called before javac compilation + -post-compile: called after javac compilation + -pre-compile-single: called before javac compilation of single file + -post-compile-single: called after javac compilation of single file + -pre-compile-test: called before javac compilation of JUnit tests + -post-compile-test: called after javac compilation of JUnit tests + -pre-compile-test-single: called before javac compilation of single JUnit test + -post-compile-test-single: called after javac compilation of single JUunit test + -pre-jar: called before JAR building + -post-jar: called after JAR building + -post-clean: called after cleaning build products + + (Targets beginning with '-' are not intended to be called on their own.) + + Example of inserting an obfuscator after compilation could look like this: + + <target name="-post-compile"> + <obfuscate> + <fileset dir="${build.classes.dir}"/> + </obfuscate> + </target> + + For list of available properties check the imported + nbproject/build-impl.xml file. + + + Another way to customize the build is by overriding existing main targets. + The targets of interest are: + + -init-macrodef-javac: defines macro for javac compilation + -init-macrodef-junit: defines macro for junit execution + -init-macrodef-debug: defines macro for class debugging + -init-macrodef-java: defines macro for class execution + -do-jar: JAR building + run: execution of project + -javadoc-build: Javadoc generation + test-report: JUnit report generation + + An example of overriding the target for project execution could look like this: + + <target name="run" depends="MV3500_Deliverables-impl.jar"> + <exec dir="bin" executable="launcher.exe"> + <arg file="${dist.jar}"/> + </exec> + </target> + + Notice that the overridden target depends on the jar target and not only on + the compile target as the regular run target does. Again, for a list of available + properties which you can use, check the target you are overriding in the + nbproject/build-impl.xml file. + + --> +</project> diff --git a/deliverables/nbproject/build-impl.xml b/deliverables/nbproject/build-impl.xml new file mode 100644 index 0000000000000000000000000000000000000000..2a2a85c88e12d5ab136384c1fca6f77a99af2572 --- /dev/null +++ b/deliverables/nbproject/build-impl.xml @@ -0,0 +1,1420 @@ +<?xml version="1.0" encoding="UTF-8"?> +<!-- +*** GENERATED FROM project.xml - DO NOT EDIT *** +*** EDIT ../build.xml INSTEAD *** + +For the purpose of easier reading the script +is divided into following sections: + + - initialization + - compilation + - jar + - execution + - debugging + - javadoc + - test compilation + - test execution + - test debugging + - applet + - cleanup + + --> +<project xmlns:j2seproject1="http://www.netbeans.org/ns/j2se-project/1" xmlns:j2seproject3="http://www.netbeans.org/ns/j2se-project/3" xmlns:jaxrpc="http://www.netbeans.org/ns/j2se-project/jax-rpc" basedir=".." default="default" name="MV3500_Deliverables-impl"> + <fail message="Please build using Ant 1.8.0 or higher."> + <condition> + <not> + <antversion atleast="1.8.0"/> + </not> + </condition> + </fail> + <target depends="test,jar,javadoc" description="Build and test whole project." name="default"/> + <!-- + ====================== + INITIALIZATION SECTION + ====================== + --> + <target name="-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init" name="-init-private"> + <property file="nbproject/private/config.properties"/> + <property file="nbproject/private/configs/${config}.properties"/> + <property file="nbproject/private/private.properties"/> + </target> + <target depends="-pre-init,-init-private" name="-init-user"> + <property file="${user.properties.file}"/> + <!-- The two properties below are usually overridden --> + <!-- by the active platform. Just a fallback. --> + <property name="default.javac.source" value="1.6"/> + <property name="default.javac.target" value="1.6"/> + </target> + <target depends="-pre-init,-init-private,-init-user" name="-init-project"> + <property file="nbproject/configs/${config}.properties"/> + <property file="nbproject/project.properties"/> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-init-macrodef-property" name="-do-init"> + <property name="platform.java" value="${java.home}/bin/java"/> + <available file="${manifest.file}" property="manifest.available"/> + <condition property="splashscreen.available"> + <and> + <not> + <equals arg1="${application.splash}" arg2="" trim="true"/> + </not> + <available file="${application.splash}"/> + </and> + </condition> + <condition property="main.class.available"> + <and> + <isset property="main.class"/> + <not> + <equals arg1="${main.class}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition property="profile.available"> + <and> + <isset property="javac.profile"/> + <length length="0" string="${javac.profile}" when="greater"/> + <matches pattern="((1\.[89])|9)(\..*)?" string="${javac.source}"/> + </and> + </condition> + <condition property="do.archive"> + <or> + <not> + <istrue value="${jar.archive.disabled}"/> + </not> + <istrue value="${not.archive.disabled}"/> + </or> + </condition> + <condition property="do.mkdist"> + <and> + <isset property="do.archive"/> + <isset property="libs.CopyLibs.classpath"/> + <not> + <istrue value="${mkdist.disabled}"/> + </not> + </and> + </condition> + <condition property="do.archive+manifest.available"> + <and> + <isset property="manifest.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+main.class.available"> + <and> + <isset property="main.class.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+splashscreen.available"> + <and> + <isset property="splashscreen.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="do.archive+profile.available"> + <and> + <isset property="profile.available"/> + <istrue value="${do.archive}"/> + </and> + </condition> + <condition property="have.tests"> + <or> + <available file="${test.src.dir}"/> + </or> + </condition> + <condition property="have.sources"> + <or> + <available file="${src.dir}"/> + </or> + </condition> + <condition property="netbeans.home+have.tests"> + <and> + <isset property="netbeans.home"/> + <isset property="have.tests"/> + </and> + </condition> + <condition property="no.javadoc.preview"> + <and> + <isset property="javadoc.preview"/> + <isfalse value="${javadoc.preview}"/> + </and> + </condition> + <property name="run.jvmargs" value=""/> + <property name="run.jvmargs.ide" value=""/> + <property name="javac.compilerargs" value=""/> + <property name="work.dir" value="${basedir}"/> + <condition property="no.deps"> + <and> + <istrue value="${no.dependencies}"/> + </and> + </condition> + <property name="javac.debug" value="true"/> + <property name="javadoc.preview" value="true"/> + <property name="application.args" value=""/> + <property name="source.encoding" value="${file.encoding}"/> + <property name="runtime.encoding" value="${source.encoding}"/> + <property name="manifest.encoding" value="${source.encoding}"/> + <condition property="javadoc.encoding.used" value="${javadoc.encoding}"> + <and> + <isset property="javadoc.encoding"/> + <not> + <equals arg1="${javadoc.encoding}" arg2=""/> + </not> + </and> + </condition> + <property name="javadoc.encoding.used" value="${source.encoding}"/> + <property name="includes" value="**"/> + <property name="excludes" value=""/> + <property name="do.depend" value="false"/> + <condition property="do.depend.true"> + <istrue value="${do.depend}"/> + </condition> + <path id="endorsed.classpath.path" path="${endorsed.classpath}"/> + <condition else="" property="endorsed.classpath.cmd.line.arg" value="-Xbootclasspath/p:'${toString:endorsed.classpath.path}'"> + <and> + <isset property="endorsed.classpath"/> + <not> + <equals arg1="${endorsed.classpath}" arg2="" trim="true"/> + </not> + </and> + </condition> + <condition else="" property="javac.profile.cmd.line.arg" value="-profile ${javac.profile}"> + <isset property="profile.available"/> + </condition> + <condition else="false" property="jdkBug6558476"> + <and> + <matches pattern="1\.[56]" string="${java.specification.version}"/> + <not> + <os family="unix"/> + </not> + </and> + </condition> + <condition else="false" property="javac.fork"> + <or> + <istrue value="${jdkBug6558476}"/> + <istrue value="${javac.external.vm}"/> + </or> + </condition> + <property name="jar.index" value="false"/> + <property name="jar.index.metainf" value="${jar.index}"/> + <property name="copylibs.rebase" value="true"/> + <available file="${meta.inf.dir}/persistence.xml" property="has.persistence.xml"/> + <condition property="junit.available"> + <or> + <available classname="org.junit.Test" classpath="${run.test.classpath}"/> + <available classname="junit.framework.Test" classpath="${run.test.classpath}"/> + </or> + </condition> + <condition property="testng.available"> + <available classname="org.testng.annotations.Test" classpath="${run.test.classpath}"/> + </condition> + <condition property="junit+testng.available"> + <and> + <istrue value="${junit.available}"/> + <istrue value="${testng.available}"/> + </and> + </condition> + <condition else="testng" property="testng.mode" value="mixed"> + <istrue value="${junit+testng.available}"/> + </condition> + <condition else="" property="testng.debug.mode" value="-mixed"> + <istrue value="${junit+testng.available}"/> + </condition> + <property name="java.failonerror" value="true"/> + </target> + <target name="-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init" name="-init-check"> + <fail unless="src.dir">Must set src.dir</fail> + <fail unless="test.src.dir">Must set test.src.dir</fail> + <fail unless="build.dir">Must set build.dir</fail> + <fail unless="dist.dir">Must set dist.dir</fail> + <fail unless="build.classes.dir">Must set build.classes.dir</fail> + <fail unless="dist.javadoc.dir">Must set dist.javadoc.dir</fail> + <fail unless="build.test.classes.dir">Must set build.test.classes.dir</fail> + <fail unless="build.test.results.dir">Must set build.test.results.dir</fail> + <fail unless="build.classes.excludes">Must set build.classes.excludes</fail> + <fail unless="dist.jar">Must set dist.jar</fail> + </target> + <target name="-init-macrodef-property"> + <macrodef name="property" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${@{value}}"/> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-macrodef-javac-with-processors"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <mkdir dir="@{apgeneratedsrcdir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.profile.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <compilerarg value="-processorpath"/> + <compilerarg path="@{processorpath}:${empty.dir}"/> + <compilerarg line="${ap.processors.internal}"/> + <compilerarg line="${annotation.processing.processor.options}"/> + <compilerarg value="-s"/> + <compilerarg path="@{apgeneratedsrcdir}"/> + <compilerarg line="${ap.proc.none.internal}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-ap-cmdline-properties" name="-init-macrodef-javac-without-processors" unless="ap.supported.internal"> + <macrodef name="javac" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <attribute default="${javac.processorpath}" name="processorpath"/> + <attribute default="${build.generated.sources.dir}/ap-source-output" name="apgeneratedsrcdir"/> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="${javac.debug}" name="debug"/> + <attribute default="${empty.dir}" name="sourcepath"/> + <attribute default="${empty.dir}" name="gensrcdir"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.dir}/empty" name="empty.dir"/> + <mkdir dir="${empty.dir}"/> + <javac debug="@{debug}" deprecation="${javac.deprecation}" destdir="@{destdir}" encoding="${source.encoding}" excludes="@{excludes}" fork="${javac.fork}" includeantruntime="false" includes="@{includes}" source="${javac.source}" sourcepath="@{sourcepath}" srcdir="@{srcdir}" target="${javac.target}" tempdir="${java.io.tmpdir}"> + <src> + <dirset dir="@{gensrcdir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </src> + <classpath> + <path path="@{classpath}"/> + </classpath> + <compilerarg line="${endorsed.classpath.cmd.line.arg}"/> + <compilerarg line="${javac.profile.cmd.line.arg}"/> + <compilerarg line="${javac.compilerargs}"/> + <customize/> + </javac> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-javac-with-processors,-init-macrodef-javac-without-processors" name="-init-macrodef-javac"> + <macrodef name="depend" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${src.dir}" name="srcdir"/> + <attribute default="${build.classes.dir}" name="destdir"/> + <attribute default="${javac.classpath}" name="classpath"/> + <sequential> + <depend cache="${build.dir}/depcache" destdir="@{destdir}" excludes="${excludes}" includes="${includes}" srcdir="@{srcdir}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </depend> + </sequential> + </macrodef> + <macrodef name="force-recompile" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${build.classes.dir}" name="destdir"/> + <sequential> + <fail unless="javac.includes">Must set javac.includes</fail> + <pathconvert pathsep="${line.separator}" property="javac.includes.binary"> + <path> + <filelist dir="@{destdir}" files="${javac.includes}"/> + </path> + <globmapper from="*.java" to="*.class"/> + </pathconvert> + <tempfile deleteonexit="true" property="javac.includesfile.binary"/> + <echo file="${javac.includesfile.binary}" message="${javac.includes.binary}"/> + <delete> + <files includesfile="${javac.includesfile.binary}"/> + </delete> + <delete> + <fileset file="${javac.includesfile.binary}"/> + </delete> + </sequential> + </macrodef> + </target> + <target if="${junit.available}" name="-init-macrodef-junit-init"> + <condition else="false" property="nb.junit.batch" value="true"> + <and> + <istrue value="${junit.available}"/> + <not> + <isset property="test.method"/> + </not> + </and> + </condition> + <condition else="false" property="nb.junit.single" value="true"> + <and> + <istrue value="${junit.available}"/> + <isset property="test.method"/> + </and> + </condition> + </target> + <target name="-init-test-properties"> + <property name="test.binaryincludes" value="<nothing>"/> + <property name="test.binarytestincludes" value=""/> + <property name="test.binaryexcludes" value=""/> + </target> + <target if="${nb.junit.single}" name="-init-macrodef-junit-single" unless="${nb.junit.batch}"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element name="customize" optional="true"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <test methods="@{testmethods}" name="@{testincludes}" todir="${build.test.results.dir}"/> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg value="-ea"/> + <customize/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-test-properties" if="${nb.junit.batch}" name="-init-macrodef-junit-batch" unless="${nb.junit.single}"> + <macrodef name="junit" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element name="customize" optional="true"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + <fileset dir="${build.test.classes.dir}" excludes="@{excludes},${excludes},${test.binaryexcludes}" includes="${test.binaryincludes}"> + <filename name="${test.binarytestincludes}"/> + </fileset> + </batchtest> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg value="-ea"/> + <customize/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-junit-init,-init-macrodef-junit-single, -init-macrodef-junit-batch" if="${junit.available}" name="-init-macrodef-junit"/> + <target if="${testng.available}" name="-init-macrodef-testng"> + <macrodef name="testng" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element name="customize" optional="true"/> + <sequential> + <condition else="" property="testng.methods.arg" value="@{testincludes}.@{testmethods}"> + <isset property="test.method"/> + </condition> + <union id="test.set"> + <fileset dir="${test.src.dir}" excludes="@{excludes},**/*.xml,${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + </union> + <taskdef classname="org.testng.TestNGAntTask" classpath="${run.test.classpath}" name="testng"/> + <testng classfilesetref="test.set" failureProperty="tests.failed" listeners="org.testng.reporters.VerboseReporter" methods="${testng.methods.arg}" mode="${testng.mode}" outputdir="${build.test.results.dir}" suitename="MV3500_Deliverables" testname="TestNG tests" workingDir="${work.dir}"> + <xmlfileset dir="${build.test.classes.dir}" includes="@{testincludes}"/> + <propertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </propertyset> + <customize/> + </testng> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-test-impl"> + <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element implicit="true" name="customize" optional="true"/> + <sequential> + <echo>No tests executed.</echo> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-junit" if="${junit.available}" name="-init-macrodef-junit-impl"> + <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element implicit="true" name="customize" optional="true"/> + <sequential> + <j2seproject3:junit excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> + <customize/> + </j2seproject3:junit> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-testng" if="${testng.available}" name="-init-macrodef-testng-impl"> + <macrodef name="test-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element implicit="true" name="customize" optional="true"/> + <sequential> + <j2seproject3:testng excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> + <customize/> + </j2seproject3:testng> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-test-impl,-init-macrodef-junit-impl,-init-macrodef-testng-impl" name="-init-macrodef-test"> + <macrodef name="test" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <sequential> + <j2seproject3:test-impl excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> + <customize> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${run.jvmargs}"/> + <jvmarg line="${run.jvmargs.ide}"/> + </customize> + </j2seproject3:test-impl> + </sequential> + </macrodef> + </target> + <target if="${junit.available}" name="-init-macrodef-junit-debug" unless="${nb.junit.batch}"> + <macrodef name="junit-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element name="customize" optional="true"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <test methods="@{testmethods}" name="@{testincludes}" todir="${build.test.results.dir}"/> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg value="-ea"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <customize/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-test-properties" if="${nb.junit.batch}" name="-init-macrodef-junit-debug-batch"> + <macrodef name="junit-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element name="customize" optional="true"/> + <sequential> + <property name="junit.forkmode" value="perTest"/> + <junit dir="${work.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" forkmode="${junit.forkmode}" showoutput="true" tempdir="${build.dir}"> + <batchtest todir="${build.test.results.dir}"> + <fileset dir="${test.src.dir}" excludes="@{excludes},${excludes}" includes="@{includes}"> + <filename name="@{testincludes}"/> + </fileset> + <fileset dir="${build.test.classes.dir}" excludes="@{excludes},${excludes},${test.binaryexcludes}" includes="${test.binaryincludes}"> + <filename name="${test.binarytestincludes}"/> + </fileset> + </batchtest> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + <jvmarg value="-ea"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <customize/> + </junit> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-junit-debug,-init-macrodef-junit-debug-batch" if="${junit.available}" name="-init-macrodef-junit-debug-impl"> + <macrodef name="test-debug-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <element implicit="true" name="customize" optional="true"/> + <sequential> + <j2seproject3:junit-debug excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> + <customize/> + </j2seproject3:junit-debug> + </sequential> + </macrodef> + </target> + <target if="${testng.available}" name="-init-macrodef-testng-debug"> + <macrodef name="testng-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="testClass"/> + <attribute default="" name="testMethod"/> + <element name="customize2" optional="true"/> + <sequential> + <condition else="-testclass @{testClass}" property="test.class.or.method" value="-methods @{testClass}.@{testMethod}"> + <isset property="test.method"/> + </condition> + <condition else="-suitename MV3500_Deliverables -testname @{testClass} ${test.class.or.method}" property="testng.cmd.args" value="@{testClass}"> + <matches pattern=".*\.xml" string="@{testClass}"/> + </condition> + <delete dir="${build.test.results.dir}" quiet="true"/> + <mkdir dir="${build.test.results.dir}"/> + <j2seproject3:debug classname="org.testng.TestNG" classpath="${debug.test.classpath}"> + <customize> + <customize2/> + <jvmarg value="-ea"/> + <arg line="${testng.debug.mode}"/> + <arg line="-d ${build.test.results.dir}"/> + <arg line="-listener org.testng.reporters.VerboseReporter"/> + <arg line="${testng.cmd.args}"/> + </customize> + </j2seproject3:debug> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-testng-debug" if="${testng.available}" name="-init-macrodef-testng-debug-impl"> + <macrodef name="testng-debug-impl" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="testClass"/> + <attribute default="" name="testMethod"/> + <element implicit="true" name="customize2" optional="true"/> + <sequential> + <j2seproject3:testng-debug testClass="@{testClass}" testMethod="@{testMethod}"> + <customize2/> + </j2seproject3:testng-debug> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-junit-debug-impl" if="${junit.available}" name="-init-macrodef-test-debug-junit"> + <macrodef name="test-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <attribute default="${main.class}" name="testClass"/> + <attribute default="" name="testMethod"/> + <sequential> + <j2seproject3:test-debug-impl excludes="@{excludes}" includes="@{includes}" testincludes="@{testincludes}" testmethods="@{testmethods}"> + <customize> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${run.jvmargs}"/> + <jvmarg line="${run.jvmargs.ide}"/> + </customize> + </j2seproject3:test-debug-impl> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-testng-debug-impl" if="${testng.available}" name="-init-macrodef-test-debug-testng"> + <macrodef name="test-debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${includes}" name="includes"/> + <attribute default="${excludes}" name="excludes"/> + <attribute default="**" name="testincludes"/> + <attribute default="" name="testmethods"/> + <attribute default="${main.class}" name="testClass"/> + <attribute default="" name="testMethod"/> + <sequential> + <j2seproject3:testng-debug-impl testClass="@{testClass}" testMethod="@{testMethod}"> + <customize2> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + </customize2> + </j2seproject3:testng-debug-impl> + </sequential> + </macrodef> + </target> + <target depends="-init-macrodef-test-debug-junit,-init-macrodef-test-debug-testng" name="-init-macrodef-test-debug"/> + <!-- + pre NB7.2 profiling section; consider it deprecated + --> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile, -profile-init-check" if="profiler.info.jvmargs.agent" name="profile-init"/> + <target if="profiler.info.jvmargs.agent" name="-profile-pre-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="profiler.info.jvmargs.agent" name="-profile-post-init"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="profiler.info.jvmargs.agent" name="-profile-init-macrodef-profile"> + <macrodef name="resolve"> + <attribute name="name"/> + <attribute name="value"/> + <sequential> + <property name="@{name}" value="${env.@{value}}"/> + </sequential> + </macrodef> + <macrodef name="profile"> + <attribute default="${main.class}" name="classname"/> + <element name="customize" optional="true"/> + <sequential> + <property environment="env"/> + <resolve name="profiler.current.path" value="${profiler.info.pathvar}"/> + <java classname="@{classname}" dir="${profiler.info.dir}" failonerror="${java.failonerror}" fork="true" jvm="${profiler.info.jvm}"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <arg line="${application.args}"/> + <classpath> + <path path="${run.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target depends="-profile-pre-init, init, -profile-post-init, -profile-init-macrodef-profile" if="profiler.info.jvmargs.agent" name="-profile-init-check"> + <fail unless="profiler.info.jvm">Must set JVM to use for profiling in profiler.info.jvm</fail> + <fail unless="profiler.info.jvmargs.agent">Must set profiler agent JVM arguments in profiler.info.jvmargs.agent</fail> + </target> + <!-- + end of pre NB7.2 profiling section + --> + <target depends="-init-debug-args" name="-init-macrodef-nbjpda"> + <macrodef name="nbjpdastart" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="name"/> + <attribute default="${debug.classpath}" name="classpath"/> + <attribute default="" name="stopclassname"/> + <sequential> + <nbjpdastart addressproperty="jpda.address" name="@{name}" stopclassname="@{stopclassname}" transport="${debug-transport}"> + <classpath> + <path path="@{classpath}"/> + </classpath> + </nbjpdastart> + </sequential> + </macrodef> + <macrodef name="nbjpdareload" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${build.classes.dir}" name="dir"/> + <sequential> + <nbjpdareload> + <fileset dir="@{dir}" includes="${fix.classes}"> + <include name="${fix.includes}*.class"/> + </fileset> + </nbjpdareload> + </sequential> + </macrodef> + </target> + <target name="-init-debug-args"> + <property name="version-output" value="java version "${ant.java.version}"/> + <condition property="have-jdk-older-than-1.4"> + <or> + <contains string="${version-output}" substring="java version "1.0"/> + <contains string="${version-output}" substring="java version "1.1"/> + <contains string="${version-output}" substring="java version "1.2"/> + <contains string="${version-output}" substring="java version "1.3"/> + </or> + </condition> + <condition else="-Xdebug" property="debug-args-line" value="-Xdebug -Xnoagent -Djava.compiler=none"> + <istrue value="${have-jdk-older-than-1.4}"/> + </condition> + <condition else="dt_socket" property="debug-transport-by-os" value="dt_shmem"> + <os family="windows"/> + </condition> + <condition else="${debug-transport-by-os}" property="debug-transport" value="${debug.transport}"> + <isset property="debug.transport"/> + </condition> + </target> + <target depends="-init-debug-args" name="-init-macrodef-debug"> + <macrodef name="debug" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${debug.classpath}" name="classpath"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg line="${debug-args-line}"/> + <jvmarg value="-Xrunjdwp:transport=${debug-transport},address=${jpda.address}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <jvmarg line="${run.jvmargs.ide}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-java"> + <macrodef name="java" uri="http://www.netbeans.org/ns/j2se-project/1"> + <attribute default="${main.class}" name="classname"/> + <attribute default="${run.classpath}" name="classpath"/> + <attribute default="jvm" name="jvm"/> + <element name="customize" optional="true"/> + <sequential> + <java classname="@{classname}" dir="${work.dir}" failonerror="${java.failonerror}" fork="true"> + <jvmarg line="${endorsed.classpath.cmd.line.arg}"/> + <jvmarg value="-Dfile.encoding=${runtime.encoding}"/> + <redirector errorencoding="${runtime.encoding}" inputencoding="${runtime.encoding}" outputencoding="${runtime.encoding}"/> + <jvmarg line="${run.jvmargs}"/> + <jvmarg line="${run.jvmargs.ide}"/> + <classpath> + <path path="@{classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="run-sys-prop."/> + <mapper from="run-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <customize/> + </java> + </sequential> + </macrodef> + </target> + <target name="-init-macrodef-copylibs"> + <macrodef name="copylibs" uri="http://www.netbeans.org/ns/j2se-project/3"> + <attribute default="${manifest.file}" name="manifest"/> + <element name="customize" optional="true"/> + <sequential> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <pathconvert property="run.classpath.without.build.classes.dir"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to=""/> + </pathconvert> + <pathconvert pathsep=" " property="jar.classpath"> + <path path="${run.classpath.without.build.classes.dir}"/> + <chainedmapper> + <flattenmapper/> + <filtermapper> + <replacestring from=" " to="%20"/> + </filtermapper> + <globmapper from="*" to="lib/*"/> + </chainedmapper> + </pathconvert> + <taskdef classname="org.netbeans.modules.java.j2seproject.copylibstask.CopyLibs" classpath="${libs.CopyLibs.classpath}" name="copylibs"/> + <copylibs compress="${jar.compress}" excludeFromCopy="${copylibs.excludes}" index="${jar.index}" indexMetaInf="${jar.index.metainf}" jarfile="${dist.jar}" manifest="@{manifest}" manifestencoding="UTF-8" rebase="${copylibs.rebase}" runtimeclasspath="${run.classpath.without.build.classes.dir}"> + <fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/> + <manifest> + <attribute name="Class-Path" value="${jar.classpath}"/> + <customize/> + </manifest> + </copylibs> + </sequential> + </macrodef> + </target> + <target name="-init-presetdef-jar"> + <presetdef name="jar" uri="http://www.netbeans.org/ns/j2se-project/1"> + <jar compress="${jar.compress}" index="${jar.index}" jarfile="${dist.jar}" manifestencoding="UTF-8"> + <j2seproject1:fileset dir="${build.classes.dir}" excludes="${dist.archive.excludes}"/> + </jar> + </presetdef> + </target> + <target name="-init-ap-cmdline-properties"> + <property name="annotation.processing.enabled" value="true"/> + <property name="annotation.processing.processors.list" value=""/> + <property name="annotation.processing.processor.options" value=""/> + <property name="annotation.processing.run.all.processors" value="true"/> + <property name="javac.processorpath" value="${javac.classpath}"/> + <property name="javac.test.processorpath" value="${javac.test.classpath}"/> + <condition property="ap.supported.internal" value="true"> + <not> + <matches pattern="1\.[0-5](\..*)?" string="${javac.source}"/> + </not> + </condition> + </target> + <target depends="-init-ap-cmdline-properties" if="ap.supported.internal" name="-init-ap-cmdline-supported"> + <condition else="" property="ap.processors.internal" value="-processor ${annotation.processing.processors.list}"> + <isfalse value="${annotation.processing.run.all.processors}"/> + </condition> + <condition else="" property="ap.proc.none.internal" value="-proc:none"> + <isfalse value="${annotation.processing.enabled}"/> + </condition> + </target> + <target depends="-init-ap-cmdline-properties,-init-ap-cmdline-supported" name="-init-ap-cmdline"> + <property name="ap.cmd.line.internal" value=""/> + </target> + <target depends="-pre-init,-init-private,-init-user,-init-project,-do-init,-post-init,-init-check,-init-macrodef-property,-init-macrodef-javac,-init-macrodef-test,-init-macrodef-test-debug,-init-macrodef-nbjpda,-init-macrodef-debug,-init-macrodef-java,-init-presetdef-jar,-init-ap-cmdline" name="init"/> + <!-- + =================== + COMPILATION SECTION + =================== + --> + <target name="-deps-jar-init" unless="built-jar.properties"> + <property location="${build.dir}/built-jar.properties" name="built-jar.properties"/> + <delete file="${built-jar.properties}" quiet="true"/> + </target> + <target if="already.built.jar.${basedir}" name="-warn-already-built-jar"> + <echo level="warn" message="Cycle detected: MV3500 Deliverables was already built"/> + </target> + <target depends="init,-deps-jar-init" name="deps-jar" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-jar.properties}" verbose="false"/> + <property file="${built-jar.properties}" prefix="already.built.jar."/> + <antcall target="-warn-already-built-jar"/> + <propertyfile file="${built-jar.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + </target> + <target depends="init,-check-automatic-build,-clean-after-automatic-build" name="-verify-automatic-build"/> + <target depends="init" name="-check-automatic-build"> + <available file="${build.classes.dir}/.netbeans_automatic_build" property="netbeans.automatic.build"/> + </target> + <target depends="init" if="netbeans.automatic.build" name="-clean-after-automatic-build"> + <antcall target="clean"/> + </target> + <target depends="init,deps-jar" name="-pre-pre-compile"> + <mkdir dir="${build.classes.dir}"/> + </target> + <target name="-pre-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-depend"> + <pathconvert property="build.generated.subdirs"> + <dirset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="*"/> + </dirset> + </pathconvert> + <j2seproject3:depend srcdir="${src.dir}:${build.generated.subdirs}"/> + </target> + <target depends="init,deps-jar,-pre-pre-compile,-pre-compile, -copy-persistence-xml,-compile-depend" if="have.sources" name="-do-compile"> + <j2seproject3:javac gensrcdir="${build.generated.sources.dir}"/> + <copy todir="${build.classes.dir}"> + <fileset dir="${src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target if="has.persistence.xml" name="-copy-persistence-xml"> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy todir="${build.classes.dir}/META-INF"> + <fileset dir="${meta.inf.dir}" includes="persistence.xml orm.xml"/> + </copy> + </target> + <target name="-post-compile"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile,-do-compile,-post-compile" description="Compile project." name="compile"/> + <target name="-pre-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-pre-pre-compile" name="-do-compile-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile/> + <j2seproject3:javac excludes="" gensrcdir="${build.generated.sources.dir}" includes="${javac.includes}" sourcepath="${src.dir}"/> + </target> + <target name="-post-compile-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,-verify-automatic-build,-pre-pre-compile,-pre-compile-single,-do-compile-single,-post-compile-single" name="compile-single"/> + <!-- + ==================== + JAR BUILDING SECTION + ==================== + --> + <target depends="init" name="-pre-pre-jar"> + <dirname file="${dist.jar}" property="dist.jar.dir"/> + <mkdir dir="${dist.jar.dir}"/> + </target> + <target name="-pre-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init" if="do.archive" name="-do-jar-create-manifest" unless="manifest.available"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <touch file="${tmp.manifest.file}" verbose="false"/> + </target> + <target depends="init" if="do.archive+manifest.available" name="-do-jar-copy-manifest"> + <tempfile deleteonexit="true" destdir="${build.dir}" property="tmp.manifest.file"/> + <copy encoding="${manifest.encoding}" file="${manifest.file}" outputencoding="UTF-8" tofile="${tmp.manifest.file}"/> + </target> + <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+main.class.available" name="-do-jar-set-mainclass"> + <manifest encoding="UTF-8" file="${tmp.manifest.file}" mode="update"> + <attribute name="Main-Class" value="${main.class}"/> + </manifest> + </target> + <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+profile.available" name="-do-jar-set-profile"> + <manifest encoding="UTF-8" file="${tmp.manifest.file}" mode="update"> + <attribute name="Profile" value="${javac.profile}"/> + </manifest> + </target> + <target depends="init,-do-jar-create-manifest,-do-jar-copy-manifest" if="do.archive+splashscreen.available" name="-do-jar-set-splashscreen"> + <basename file="${application.splash}" property="splashscreen.basename"/> + <mkdir dir="${build.classes.dir}/META-INF"/> + <copy failonerror="false" file="${application.splash}" todir="${build.classes.dir}/META-INF"/> + <manifest encoding="UTF-8" file="${tmp.manifest.file}" mode="update"> + <attribute name="SplashScreen-Image" value="META-INF/${splashscreen.basename}"/> + </manifest> + </target> + <target depends="init,-init-macrodef-copylibs,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.mkdist" name="-do-jar-copylibs"> + <j2seproject3:copylibs manifest="${tmp.manifest.file}"/> + <echo level="info">To run this application from the command line without Ant, try:</echo> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <echo level="info">java -jar "${dist.jar.resolved}"</echo> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen" if="do.archive" name="-do-jar-jar" unless="do.mkdist"> + <j2seproject1:jar manifest="${tmp.manifest.file}"/> + <property location="${build.classes.dir}" name="build.classes.dir.resolved"/> + <property location="${dist.jar}" name="dist.jar.resolved"/> + <pathconvert property="run.classpath.with.dist.jar"> + <path path="${run.classpath}"/> + <map from="${build.classes.dir.resolved}" to="${dist.jar.resolved}"/> + </pathconvert> + <condition else="" property="jar.usage.message" value="To run this application from the command line without Ant, try:${line.separator}${platform.java} -cp ${run.classpath.with.dist.jar} ${main.class}"> + <isset property="main.class.available"/> + </condition> + <condition else="debug" property="jar.usage.level" value="info"> + <isset property="main.class.available"/> + </condition> + <echo level="${jar.usage.level}" message="${jar.usage.message}"/> + </target> + <target depends="-do-jar-copylibs" if="do.archive" name="-do-jar-delete-manifest"> + <delete> + <fileset file="${tmp.manifest.file}"/> + </delete> + </target> + <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-jar,-do-jar-delete-manifest" name="-do-jar-without-libraries"/> + <target depends="init,compile,-pre-pre-jar,-pre-jar,-do-jar-create-manifest,-do-jar-copy-manifest,-do-jar-set-mainclass,-do-jar-set-profile,-do-jar-set-splashscreen,-do-jar-copylibs,-do-jar-delete-manifest" name="-do-jar-with-libraries"/> + <target name="-post-jar"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-jar,-do-jar-without-libraries,-do-jar-with-libraries,-post-jar" name="-do-jar"/> + <target depends="init,compile,-pre-jar,-do-jar,-post-jar" description="Build JAR." name="jar"/> + <!-- + ================= + EXECUTION SECTION + ================= + --> + <target depends="init,compile" description="Run a main class." name="run"> + <j2seproject1:java> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject1:java> + </target> + <target name="-do-not-recompile"> + <property name="javac.includes.binary" value=""/> + </target> + <target depends="init,compile-single" name="run-single"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}"/> + </target> + <target depends="init,compile-test-single" name="run-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <j2seproject1:java classname="${run.class}" classpath="${run.test.classpath}"/> + </target> + <!-- + ================= + DEBUGGING SECTION + ================= + --> + <target depends="init" if="netbeans.home" name="-debug-start-debugger"> + <j2seproject1:nbjpdastart name="${debug.class}"/> + </target> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-main-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${debug.class}"/> + </target> + <target depends="init,compile" name="-debug-start-debuggee"> + <j2seproject3:debug> + <customize> + <arg line="${application.args}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile,-debug-start-debugger,-debug-start-debuggee" description="Debug project in IDE." if="netbeans.home" name="debug"/> + <target depends="init" if="netbeans.home" name="-debug-start-debugger-stepinto"> + <j2seproject1:nbjpdastart stopclassname="${main.class}"/> + </target> + <target depends="init,compile,-debug-start-debugger-stepinto,-debug-start-debuggee" if="netbeans.home" name="debug-stepinto"/> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-single"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}"/> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-single" if="netbeans.home" name="debug-single"/> + <target depends="init,compile-test-single" if="netbeans.home" name="-debug-start-debuggee-main-test"> + <fail unless="debug.class">Must select one file in the IDE or set debug.class</fail> + <j2seproject3:debug classname="${debug.class}" classpath="${debug.test.classpath}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-main-test,-debug-start-debuggee-main-test" if="netbeans.home" name="debug-test-with-main"/> + <target depends="init" name="-pre-debug-fix"> + <fail unless="fix.includes">Must set fix.includes</fail> + <property name="javac.includes" value="${fix.includes}.java"/> + </target> + <target depends="init,-pre-debug-fix,compile-single" if="netbeans.home" name="-do-debug-fix"> + <j2seproject1:nbjpdareload/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix" if="netbeans.home" name="debug-fix"/> + <!-- + ================= + PROFILING SECTION + ================= + --> + <!-- + pre NB7.2 profiler integration + --> + <target depends="profile-init,compile" description="Profile a project in the IDE." if="profiler.info.jvmargs.agent" name="-profile-pre72"> + <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile/> + </target> + <target depends="profile-init,compile-single" description="Profile a selected class in the IDE." if="profiler.info.jvmargs.agent" name="-profile-single-pre72"> + <fail unless="profile.class">Must select one file in the IDE or set profile.class</fail> + <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="${profile.class}"/> + </target> + <target depends="profile-init,compile-single" if="profiler.info.jvmargs.agent" name="-profile-applet-pre72"> + <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> + <nbprofiledirect> + <classpath> + <path path="${run.classpath}"/> + </classpath> + </nbprofiledirect> + <profile classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </profile> + </target> + <target depends="profile-init,compile-test-single" if="profiler.info.jvmargs.agent" name="-profile-test-single-pre72"> + <fail unless="netbeans.home">This target only works when run from inside the NetBeans IDE.</fail> + <nbprofiledirect> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + </nbprofiledirect> + <junit dir="${profiler.info.dir}" errorproperty="tests.failed" failureproperty="tests.failed" fork="true" jvm="${profiler.info.jvm}" showoutput="true"> + <env key="${profiler.info.pathvar}" path="${profiler.info.agentpath}:${profiler.current.path}"/> + <jvmarg value="${profiler.info.jvmargs.agent}"/> + <jvmarg line="${profiler.info.jvmargs}"/> + <test name="${profile.class}"/> + <classpath> + <path path="${run.test.classpath}"/> + </classpath> + <syspropertyset> + <propertyref prefix="test-sys-prop."/> + <mapper from="test-sys-prop.*" to="*" type="glob"/> + </syspropertyset> + <formatter type="brief" usefile="false"/> + <formatter type="xml"/> + </junit> + </target> + <!-- + end of pre NB72 profiling section + --> + <target if="netbeans.home" name="-profile-check"> + <condition property="profiler.configured"> + <or> + <contains casesensitive="true" string="${run.jvmargs.ide}" substring="-agentpath:"/> + <contains casesensitive="true" string="${run.jvmargs.ide}" substring="-javaagent:"/> + </or> + </condition> + </target> + <target depends="-profile-check,-profile-pre72" description="Profile a project in the IDE." if="profiler.configured" name="profile" unless="profiler.info.jvmargs.agent"> + <startprofiler/> + <antcall target="run"/> + </target> + <target depends="-profile-check,-profile-single-pre72" description="Profile a selected class in the IDE." if="profiler.configured" name="profile-single" unless="profiler.info.jvmargs.agent"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <startprofiler/> + <antcall target="run-single"/> + </target> + <target depends="-profile-test-single-pre72" description="Profile a selected test in the IDE." name="profile-test-single"/> + <target depends="-profile-check" description="Profile a selected test in the IDE." if="profiler.configured" name="profile-test" unless="profiler.info.jvmargs"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <startprofiler/> + <antcall target="test-single"/> + </target> + <target depends="-profile-check" description="Profile a selected class in the IDE." if="profiler.configured" name="profile-test-with-main"> + <fail unless="run.class">Must select one file in the IDE or set run.class</fail> + <startprofiler/> + <antcall target="run-test-with-main"/> + </target> + <target depends="-profile-check,-profile-applet-pre72" if="profiler.configured" name="profile-applet" unless="profiler.info.jvmargs.agent"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <startprofiler/> + <antcall target="run-applet"/> + </target> + <!-- + =============== + JAVADOC SECTION + =============== + --> + <target depends="init" if="have.sources" name="-javadoc-build"> + <mkdir dir="${dist.javadoc.dir}"/> + <condition else="" property="javadoc.endorsed.classpath.cmd.line.arg" value="-J${endorsed.classpath.cmd.line.arg}"> + <and> + <isset property="endorsed.classpath.cmd.line.arg"/> + <not> + <equals arg1="${endorsed.classpath.cmd.line.arg}" arg2=""/> + </not> + </and> + </condition> + <condition else="" property="bug5101868workaround" value="*.java"> + <matches pattern="1\.[56](\..*)?" string="${java.version}"/> + </condition> + <javadoc additionalparam="-J-Dfile.encoding=${file.encoding} ${javadoc.additionalparam}" author="${javadoc.author}" charset="UTF-8" destdir="${dist.javadoc.dir}" docencoding="UTF-8" encoding="${javadoc.encoding.used}" failonerror="true" noindex="${javadoc.noindex}" nonavbar="${javadoc.nonavbar}" notree="${javadoc.notree}" private="${javadoc.private}" source="${javac.source}" splitindex="${javadoc.splitindex}" use="${javadoc.use}" useexternalfile="true" version="${javadoc.version}" windowtitle="${javadoc.windowtitle}"> + <classpath> + <path path="${javac.classpath}"/> + </classpath> + <fileset dir="${src.dir}" excludes="${bug5101868workaround},${excludes}" includes="${includes}"> + <filename name="**/*.java"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/*.java"/> + <exclude name="*.java"/> + </fileset> + <arg line="${javadoc.endorsed.classpath.cmd.line.arg}"/> + </javadoc> + <copy todir="${dist.javadoc.dir}"> + <fileset dir="${src.dir}" excludes="${excludes}" includes="${includes}"> + <filename name="**/doc-files/**"/> + </fileset> + <fileset dir="${build.generated.sources.dir}" erroronmissingdir="false"> + <include name="**/doc-files/**"/> + </fileset> + </copy> + </target> + <target depends="init,-javadoc-build" if="netbeans.home" name="-javadoc-browse" unless="no.javadoc.preview"> + <nbbrowse file="${dist.javadoc.dir}/index.html"/> + </target> + <target depends="init,-javadoc-build,-javadoc-browse" description="Build Javadoc." name="javadoc"/> + <!-- + ========================= + TEST COMPILATION SECTION + ========================= + --> + <target depends="init,compile" if="have.tests" name="-pre-pre-compile-test"> + <mkdir dir="${build.test.classes.dir}"/> + </target> + <target name="-pre-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target if="do.depend.true" name="-compile-test-depend"> + <j2seproject3:depend classpath="${javac.test.classpath}" destdir="${build.test.classes.dir}" srcdir="${test.src.dir}"/> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test,-compile-test-depend" if="have.tests" name="-do-compile-test"> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" processorpath="${javac.test.processorpath}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test,-do-compile-test,-post-compile-test" name="compile-test"/> + <target name="-pre-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-jar,compile,-pre-pre-compile-test,-pre-compile-test-single" if="have.tests" name="-do-compile-test-single"> + <fail unless="javac.includes">Must select some files in the IDE or set javac.includes</fail> + <j2seproject3:force-recompile destdir="${build.test.classes.dir}"/> + <j2seproject3:javac apgeneratedsrcdir="${build.test.classes.dir}" classpath="${javac.test.classpath}" debug="true" destdir="${build.test.classes.dir}" excludes="" includes="${javac.includes}" processorpath="${javac.test.processorpath}" sourcepath="${test.src.dir}" srcdir="${test.src.dir}"/> + <copy todir="${build.test.classes.dir}"> + <fileset dir="${test.src.dir}" excludes="${build.classes.excludes},${excludes}" includes="${includes}"/> + </copy> + </target> + <target name="-post-compile-test-single"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,compile,-pre-pre-compile-test,-pre-compile-test-single,-do-compile-test-single,-post-compile-test-single" name="compile-test-single"/> + <!-- + ======================= + TEST EXECUTION SECTION + ======================= + --> + <target depends="init" if="have.tests" name="-pre-test-run"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test,-pre-test-run" if="have.tests" name="-do-test-run"> + <j2seproject3:test includes="${includes}" testincludes="**/*Test.java"/> + </target> + <target depends="init,compile-test,-pre-test-run,-do-test-run" if="have.tests" name="-post-test-run"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init" if="have.tests" name="test-report"/> + <target depends="init" if="netbeans.home+have.tests" name="-test-browse"/> + <target depends="init,compile-test,-pre-test-run,-do-test-run,test-report,-post-test-run,-test-browse" description="Run unit tests." name="test"/> + <target depends="init" if="have.tests" name="-pre-test-run-single"> + <mkdir dir="${build.test.results.dir}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single"> + <fail unless="test.includes">Must select some files in the IDE or set test.includes</fail> + <j2seproject3:test excludes="" includes="${test.includes}" testincludes="${test.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single" if="have.tests" name="-post-test-run-single"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single,-post-test-run-single" description="Run single unit test." name="test-single"/> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-do-test-run-single-method"> + <fail unless="test.class">Must select some files in the IDE or set test.class</fail> + <fail unless="test.method">Must select some method in the IDE or set test.method</fail> + <j2seproject3:test excludes="" includes="${javac.includes}" testincludes="${test.class}" testmethods="${test.method}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single-method" if="have.tests" name="-post-test-run-single-method"> + <fail if="tests.failed" unless="ignore.failing.tests">Some tests failed; see details above.</fail> + </target> + <target depends="init,compile-test-single,-pre-test-run-single,-do-test-run-single-method,-post-test-run-single-method" description="Run single unit test." name="test-single-method"/> + <!-- + ======================= + TEST DEBUGGING SECTION + ======================= + --> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-debug-start-debuggee-test"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <j2seproject3:test-debug excludes="" includes="${javac.includes}" testClass="${test.class}" testincludes="${javac.includes}"/> + </target> + <target depends="init,compile-test-single,-pre-test-run-single" if="have.tests" name="-debug-start-debuggee-test-method"> + <fail unless="test.class">Must select one file in the IDE or set test.class</fail> + <fail unless="test.method">Must select some method in the IDE or set test.method</fail> + <j2seproject3:test-debug excludes="" includes="${javac.includes}" testClass="${test.class}" testMethod="${test.method}" testincludes="${test.class}" testmethods="${test.method}"/> + </target> + <target depends="init,compile-test" if="netbeans.home+have.tests" name="-debug-start-debugger-test"> + <j2seproject1:nbjpdastart classpath="${debug.test.classpath}" name="${test.class}"/> + </target> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test" name="debug-test"/> + <target depends="init,compile-test-single,-debug-start-debugger-test,-debug-start-debuggee-test-method" name="debug-test-method"/> + <target depends="init,-pre-debug-fix,compile-test-single" if="netbeans.home" name="-do-debug-fix-test"> + <j2seproject1:nbjpdareload dir="${build.test.classes.dir}"/> + </target> + <target depends="init,-pre-debug-fix,-do-debug-fix-test" if="netbeans.home" name="debug-fix-test"/> + <!-- + ========================= + APPLET EXECUTION SECTION + ========================= + --> + <target depends="init,compile-single" name="run-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject1:java classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject1:java> + </target> + <!-- + ========================= + APPLET DEBUGGING SECTION + ========================= + --> + <target depends="init,compile-single" if="netbeans.home" name="-debug-start-debuggee-applet"> + <fail unless="applet.url">Must select one file in the IDE or set applet.url</fail> + <j2seproject3:debug classname="sun.applet.AppletViewer"> + <customize> + <arg value="${applet.url}"/> + </customize> + </j2seproject3:debug> + </target> + <target depends="init,compile-single,-debug-start-debugger,-debug-start-debuggee-applet" if="netbeans.home" name="debug-applet"/> + <!-- + =============== + CLEANUP SECTION + =============== + --> + <target name="-deps-clean-init" unless="built-clean.properties"> + <property location="${build.dir}/built-clean.properties" name="built-clean.properties"/> + <delete file="${built-clean.properties}" quiet="true"/> + </target> + <target if="already.built.clean.${basedir}" name="-warn-already-built-clean"> + <echo level="warn" message="Cycle detected: MV3500 Deliverables was already built"/> + </target> + <target depends="init,-deps-clean-init" name="deps-clean" unless="no.deps"> + <mkdir dir="${build.dir}"/> + <touch file="${built-clean.properties}" verbose="false"/> + <property file="${built-clean.properties}" prefix="already.built.clean."/> + <antcall target="-warn-already-built-clean"/> + <propertyfile file="${built-clean.properties}"> + <entry key="${basedir}" value=""/> + </propertyfile> + </target> + <target depends="init" name="-do-clean"> + <delete dir="${build.dir}"/> + <delete dir="${dist.dir}" followsymlinks="false" includeemptydirs="true"/> + </target> + <target name="-post-clean"> + <!-- Empty placeholder for easier customization. --> + <!-- You can override this target in the ../build.xml file. --> + </target> + <target depends="init,deps-clean,-do-clean,-post-clean" description="Clean build products." name="clean"/> + <target name="-check-call-dep"> + <property file="${call.built.properties}" prefix="already.built."/> + <condition property="should.call.dep"> + <and> + <not> + <isset property="already.built.${call.subproject}"/> + </not> + <available file="${call.script}"/> + </and> + </condition> + </target> + <target depends="-check-call-dep" if="should.call.dep" name="-maybe-call-dep"> + <ant antfile="${call.script}" inheritall="false" target="${call.target}"> + <propertyset> + <propertyref prefix="transfer."/> + <mapper from="transfer.*" to="*" type="glob"/> + </propertyset> + </ant> + </target> +</project> diff --git a/deliverables/nbproject/project.properties b/deliverables/nbproject/project.properties new file mode 100644 index 0000000000000000000000000000000000000000..749fb22f3de7a1f6fb70257e0554b050cf760256 --- /dev/null +++ b/deliverables/nbproject/project.properties @@ -0,0 +1,72 @@ +annotation.processing.enabled=true +annotation.processing.enabled.in.editor=false +annotation.processing.processor.options= +annotation.processing.processors.list= +annotation.processing.run.all.processors=true +annotation.processing.source.output=${build.generated.sources.dir}/ap-source-output +build.classes.dir=${build.dir}/classes +build.classes.excludes=**/*.java,**/*.form +# This directory is removed when the project is cleaned: +build.dir=build +build.generated.dir=${build.dir}/generated +build.generated.sources.dir=${build.dir}/generated-sources +# Only compile against the classpath explicitly listed here: +build.sysclasspath=ignore +build.test.classes.dir=${build.dir}/test/classes +build.test.results.dir=${build.dir}/test/results +# Uncomment to specify the preferred debugger connection transport: +#debug.transport=dt_socket +debug.classpath=\ + ${run.classpath} +debug.test.classpath=\ + ${run.test.classpath} +# Files in build.classes.dir which should be excluded from distribution jar +dist.archive.excludes= +# This directory is removed when the project is cleaned: +dist.dir=dist +dist.jar=${dist.dir}/MV3500_Deliverables.jar +dist.javadoc.dir=${dist.dir}/javadoc +excludes= +includes=** +jar.compress=false +javac.classpath= +# Space-separated list of extra javac options +javac.compilerargs= +javac.deprecation=false +javac.external.vm=true +javac.processorpath=\ + ${javac.classpath} +javac.source=1.8 +javac.target=1.8 +javac.test.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +javac.test.processorpath=\ + ${javac.test.classpath} +javadoc.additionalparam= +javadoc.author=false +javadoc.encoding=${source.encoding} +javadoc.noindex=false +javadoc.nonavbar=false +javadoc.notree=false +javadoc.private=false +javadoc.splitindex=true +javadoc.use=true +javadoc.version=false +javadoc.windowtitle= +meta.inf.dir=${src.dir}/META-INF +mkdist.disabled=true +platform.active=default_platform +run.classpath=\ + ${javac.classpath}:\ + ${build.classes.dir} +# Space-separated list of JVM arguments used when running the project. +# You may also define separate properties like run-sys-prop.name=value instead of -Dname=value. +# To set system properties for unit tests define test-sys-prop.name=value: +run.jvmargs= +run.test.classpath=\ + ${javac.test.classpath}:\ + ${build.test.classes.dir} +source.encoding=UTF-8 +src.dir=src +test.src.dir=test diff --git a/deliverables/nbproject/project.xml b/deliverables/nbproject/project.xml new file mode 100644 index 0000000000000000000000000000000000000000..1d2ea4beb4f7f8320e545e1a40ae4d3b59682874 --- /dev/null +++ b/deliverables/nbproject/project.xml @@ -0,0 +1,15 @@ +<?xml version="1.0" encoding="UTF-8"?> +<project xmlns="http://www.netbeans.org/ns/project/1"> + <type>org.netbeans.modules.java.j2seproject</type> + <configuration> + <data xmlns="http://www.netbeans.org/ns/j2se-project/3"> + <name>MV3500 Deliverables</name> + <source-roots> + <root id="src.dir"/> + </source-roots> + <test-roots> + <root id="test.src.dir"/> + </test-roots> + </data> + </configuration> +</project> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverAtoTCP.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverAtoTCP.java new file mode 100644 index 0000000000000000000000000000000000000000..796b84bca6450614eeee4b19cb64358e76ccd59d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverAtoTCP.java @@ -0,0 +1,99 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + +import java.net.*; +import java.util.*; + +import edu.nps.moves.disutil.*; +import edu.nps.moves.dis.*; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; + +/** + * Receives PDUs from the network creates a TCP connection, then + * sends information to through the connection. + * + * @author Angelopoulos/Blankenbeker + * @version 8 MAR 2018 + */ +public class AngelBlankEspduReceiverAtoTCP { + + public static final String TCP_DESTINATION_IP = "172.20.146.111"; + public static final int DIS_DESTINATION_PORT = 3000; + public static final int TCP_DESTINATION_PORT = 2999; + public static final int MAX_PDU_SIZE = 8192; + public static final String GROUP = "239.1.2.4"; + + public static void main(String args[]) { + MulticastSocket socket; + DatagramSocket dataGram; + DatagramPacket packet; + InetAddress address; + PduFactory pduFactory = new PduFactory(); + try { + // Specify the socket to receive data + socket = new MulticastSocket(DIS_DESTINATION_PORT); + socket.setBroadcast(true); + + address = InetAddress.getByName(GROUP); + socket.joinGroup(address); + + //System.out.println("Joined Group."); + // Loop infinitely, receiving datagrams + while (true) { + try + { + + byte buffer[] = new byte[MAX_PDU_SIZE]; + packet = new DatagramPacket(buffer, buffer.length); + + socket.receive(packet); + //System.out.println("Packet Received"); + + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(packet.getData()); + //System.out.println("Bundle size is " + pduBundle.size()); + + Iterator it = pduBundle.iterator(); + + while(it.hasNext()) + { + Pdu aPdu = (Pdu)it.next(); + + // System.out.print("got PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu) + { + + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + if (eid.getSite() == 100) + { + dataGram = new DatagramSocket(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + aPdu.marshal(dos); + byte[] data = baos.toByteArray(); + + DatagramPacket DpSend = new DatagramPacket(data, data.length, InetAddress.getByName(TCP_DESTINATION_IP), TCP_DESTINATION_PORT); + dataGram.send(DpSend); + System.out.println("Alpha Bridging Complete to: " + TCP_DESTINATION_IP); + //EntityType entityType = ((EntityStatePdu)aPdu).getEntityType(); + } + Vector3Double location = ((EntityStatePdu)aPdu).getEntityLocation(); + System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] "); + //System.out.print(" Location in DIS coordinates: [" + location.getX() + ", " + location.getY() + ", " + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + } + System.out.println(); + } // end trop through PDU bundle + } + catch (Exception e) { + System.out.println(e); + } + } // end while + } // End try + catch (Exception e) { + System.out.println(e); + } + } // end main +} // end class diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverBtoTCP.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverBtoTCP.java new file mode 100644 index 0000000000000000000000000000000000000000..7ecf5439b6c582ee9339b3e20eaeb05d5306e3ca --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduReceiverBtoTCP.java @@ -0,0 +1,90 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + +import java.net.*; +import java.util.*; + +import edu.nps.moves.disutil.*; +import edu.nps.moves.dis.*; +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; + + +/** + * Receives PDUs from the network in IEEE format and creates a TCP connection, + * then sends information through the connection. + * + * @author Angelopoulos/Blankenbeker + * @version 8 MAR 2018 + */ +public class AngelBlankEspduReceiverBtoTCP { + + public static final String TCP_DESTINATION_IP = "172.20.144.187"; + public static final int DIS_DESTINATION_PORT = 2800; + public static final int TCP_DESTINATION_PORT = 2998; + public static final int MAX_PDU_SIZE = 8192; + public static final String GROUP = "239.1.2.3"; + public static void main(String args[]) { + MulticastSocket socket; + DatagramPacket packet; + DatagramSocket dataGram; + InetAddress address; + PduFactory pduFactory = new PduFactory(); + + try { + + // Specify the socket to receive data + socket = new MulticastSocket(DIS_DESTINATION_PORT); + socket.setBroadcast(true); + address = InetAddress.getByName(GROUP); + socket.joinGroup(address); + //System.out.println("Joined Group."); + // Loop infinitely, receiving datagrams + while (true) { + try{ + byte buffer[] = new byte[MAX_PDU_SIZE]; + packet = new DatagramPacket(buffer, buffer.length); + socket.receive(packet); + //System.out.println("Packet Received"); + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(packet.getData()); + //System.out.println("Bundle size is " + pduBundle.size()); + Iterator it = pduBundle.iterator(); + + while(it.hasNext()){ + Pdu aPdu = (Pdu)it.next(); + //System.out.print("got PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu){ + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + if (eid.getSite() == 200){ + dataGram = new DatagramSocket(); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + aPdu.marshal(dos); + byte[] data = baos.toByteArray(); + + DatagramPacket DpSend = new DatagramPacket(data, data.length, InetAddress.getByName(TCP_DESTINATION_IP), TCP_DESTINATION_PORT); + dataGram.send(DpSend); // Create TCP Bridge + System.out.println("Bravo briding complete to: "+ TCP_DESTINATION_IP); + //EntityType entityType = ((EntityStatePdu)aPdu).getEntityType(); + } + Vector3Double location = ((EntityStatePdu)aPdu).getEntityLocation(); + System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] "); + //System.out.print(" Location in DIS coordinates: [" + location.getX() + ", " + location.getY() + ", " + position.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + } + System.out.println(); + } // end trop through PDU bundle + } + catch (Exception e) { + System.out.println(e); + } + } // end while + } // End try + catch (Exception e) { + System.out.println(e); + } + + } // end main +} // end class diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java new file mode 100644 index 0000000000000000000000000000000000000000..920f01760c7d9352b5409852d32909b079db3fdb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderA.java @@ -0,0 +1,212 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Emits PDUs from the network in IEEE format. + * + * @author Angelopoulos/Blankenbeker + * @version 8 MAR 2018 + */ +public class AngelBlankEspduSenderA +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** default multicast group we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; + + /** Port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be mcast. + * To determine bcast destination IP, use an online bcast address + * caclulator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in mcast mode, a join() will be done on the mcast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; + DisTime disTime = DisTime.getInstance(); + int alternator = -1; + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.MULTICAST; + InetAddress destinationIp = null; + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(Exception e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(DIS_DESTINATION_PORT); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(Exception e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + espdu.setExerciseID((short)1); + EntityID eid = espdu.getEntityID(); + eid.setSite(100); // 0 is apparently not a valid site number, per the spec + eid.setApplication(1); + eid.setEntity(2); + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + eid.setEntity(idx+1); + int ts = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(ts); + double direction = Math.pow((double)(-1.0), (double)(idx)); + lon = lon + (direction * 0.00006); + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + byte[] data = baos.toByteArray(); + DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); + socket.send(packet); + Thread.sleep(3000); + location = espdu.getEntityLocation(); + System.out.println("Espdu #" + idx + " EID=[" + eid.getSite() + "," + eid.getApplication() + "," + eid.getEntity() + "]"); + //System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + } + } + catch(Exception e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a bcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the bcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a bcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all bcast addresses + + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> bcastAddresses = new HashSet<InetAddress>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting bcast address for " + anAddress); + InetAddress abcast = anAddress.getBroadcast(); + if(abcast != null) + bcastAddresses.add(abcast); + } + } + } + + } + catch(Exception e) + { + e.printStackTrace(); + System.out.println(e); + } + + return bcastAddresses; + } +**/ +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java new file mode 100644 index 0000000000000000000000000000000000000000..c1303f55f421a707f86db0c05429f025214ddec8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduSenderB.java @@ -0,0 +1,212 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author Angelopoulos/Blankenbeker + * 8 MAR 2018 + */ +public class AngelBlankEspduSenderB +{ + public static final int NUMBER_TO_SEND = 5000; + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** default multicast group we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + /** Port we send on */ + public static final int DIS_DESTINATION_PORT = 2800; + +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; + DisTime disTime = DisTime.getInstance(); + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.MULTICAST; + InetAddress destinationIp = null; + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(Exception e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(DIS_DESTINATION_PORT); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + + } + } // end networkModeString + } + catch(Exception e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + + espdu.setExerciseID((short)1); + EntityID eid = espdu.getEntityID(); + eid.setSite(200); // 0 is apparently not a valid site number, per the spec + eid.setApplication(1); + eid.setEntity(2); + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + try + { + + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + eid.setEntity(idx+1); + + int ts = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(ts); + double direction = Math.pow((double)(-1.0), (double)(idx)); + lon = lon + (direction * 0.00006); + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + byte[] data = baos.toByteArray(); + DatagramPacket packet = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); + socket.send(packet); + Thread.sleep(3000); + location = espdu.getEntityLocation(); + System.out.println("Espdu #" + idx + " EID=[" + eid.getSite() + "," + eid.getApplication() + "," + eid.getEntity() + "]"); + //System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + } + } + catch(Exception e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a bcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the bcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a bcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all bcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> bcastAddresses = new HashSet<InetAddress>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting bcast address for " + anAddress); + InetAddress abcast = anAddress.getBroadcast(); + if(abcast != null) + bcastAddresses.add(abcast); + } + } + } + + } + catch(Exception e) + { + e.printStackTrace(); + System.out.println(e); + } + + return bcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java new file mode 100644 index 0000000000000000000000000000000000000000..0ec2ad18635d3b0f55fe7b97c84d558ab5f04b39 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverASenderB.java @@ -0,0 +1,192 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Listens for TCP connection from AngelBlankReciverBToTCP and sends ESPDU. + * + * @author Angelopoulos/Blankenbeker + * 8 MAR 2018 + */ +public class AngelBlankEspduTCPReceiverASenderB +{ + public static final int NUMBER_TO_SEND = 5000; + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + /** default multicast group we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + public static final int MAX_PDU_SIZE = 8192; + public static final int TCP_DESTINATION_PORT = 2999; + /** Port we send on */ + public static final int DIS_DESTINATION_PORT = 2800; +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be mcast. + * To determine bcast destination IP, use an online bcast address + * caclulator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in mcast mode, a join() will be done on the mcast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; + DisTime disTime = DisTime.getInstance(); + int alternator = -1; + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.MULTICAST; + InetAddress destinationIp = null; + PduFactory pduFactory = new PduFactory(); + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(Exception e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + Properties systemProperties = System.getProperties(); + String destinationIpString = systemProperties.getProperty("destinationIp"); + String portString = systemProperties.getProperty("port"); + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + try + { + + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(DIS_DESTINATION_PORT); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + + } + } // end networkModeString + } + catch(Exception e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + try + { + int connectionCount = 0; + DatagramSocket ds = new DatagramSocket(TCP_DESTINATION_PORT); + + while(true){ + try + { + byte buffer[] = new byte[MAX_PDU_SIZE]; + DatagramPacket tcpPacket = new DatagramPacket(buffer, buffer.length); + ds.receive(tcpPacket); + connectionCount++; + System.out.println("Current PDUs transferred over TCP: "+ connectionCount); + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(tcpPacket.getData()); + //System.out.println("Bundle size is " + pduBundle.size()); + Iterator it = pduBundle.iterator(); + + while(it.hasNext()){ + //System.out.println("Entity ID transferred: "); + Pdu aPdu = (Pdu)it.next(); + //System.out.print("got PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu){ + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + System.out.println("Entity ID transferred: "+eid.getEntity()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + aPdu.marshal(dos); + byte[] data = baos.toByteArray(); + DatagramPacket udpPacket = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); + socket.send(udpPacket); + } + } + } + catch(Exception e) + { + System.out.println(e); + } + } + } + catch(Exception e) + { + System.out.println(e); + } + +} + +/** + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> bcastAddresses = new HashSet<InetAddress>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting bcast address for " + anAddress); + InetAddress abcast = anAddress.getBroadcast(); + if(abcast != null) + bcastAddresses.add(abcast); + } + } + } + + } + catch(Exception e) + { + e.printStackTrace(); + System.out.println(e); + } + + return bcastAddresses; + } +**/ +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java new file mode 100644 index 0000000000000000000000000000000000000000..f416f253a694baf89b8acd3c2f77e7b2df07f6eb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/AngelopoulosBlankenbeker/AngelBlankEspduTCPReceiverBSenderA.java @@ -0,0 +1,206 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.AngelopoulosBlankenbeker; + + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.DisTime; +import edu.nps.moves.disutil.PduFactory; + +/** + * listens for TCP connection from AngelBlankReceiverAtoTCP and sends ESPDU in IEEE binary format. + * + * @author Angelopoulos/Blankenbeker + * @version 8 MAR 2018 + */ +public class AngelBlankEspduTCPReceiverBSenderA +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + public static final int MAX_PDU_SIZE = 8192; + /** default multicast group we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.4"; + public static final int TCP_DESTINATION_PORT = 2998; + /** Port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; + DisTime disTime = DisTime.getInstance(); + int alternator = -1; + + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.MULTICAST; + InetAddress destinationIp = null; + PduFactory pduFactory = new PduFactory(); + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(Exception e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + // Set up a socket to send information + try + { + + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(DIS_DESTINATION_PORT); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + + } + } // end networkModeString + } + catch(Exception e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + try + { + int connectionCount = 0; + DatagramSocket ds = new DatagramSocket(TCP_DESTINATION_PORT); + + while(true){ + try + { + byte buffer[] = new byte[MAX_PDU_SIZE]; + DatagramPacket tcpPacket = new DatagramPacket(buffer, buffer.length); + ds.receive(tcpPacket); + //Socket clientConnection = serverSocket.accept(); + connectionCount++; + System.out.println("Current PDUs transferred over TCP: "+ connectionCount); + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(tcpPacket.getData()); + //System.out.println("Bundle size is " + pduBundle.size()); + Iterator it = pduBundle.iterator(); + + while(it.hasNext()){ + //System.out.println("Entity ID transferred: "); + Pdu aPdu = (Pdu)it.next(); + //System.out.print("got PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu){ + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + System.out.println("Entity ID transferred: "+eid.getEntity()); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + aPdu.marshal(dos); + byte[] data = baos.toByteArray(); + DatagramPacket udpPacket = new DatagramPacket(data, data.length, InetAddress.getByName(DEFAULT_MULTICAST_GROUP), DIS_DESTINATION_PORT); + socket.send(udpPacket); + } + } + } + catch(Exception e) + { + System.out.println(e); + } + } + } + catch(Exception e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a bcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the bcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a bcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all bcast addresses + + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> bcastAddresses = new HashSet<InetAddress>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting bcast address for " + anAddress); + InetAddress abcast = anAddress.getBroadcast(); + if(abcast != null) + bcastAddresses.add(abcast); + } + } + } + + } + catch(Exception e) + { + e.printStackTrace(); + System.out.println(e); + } + + return bcastAddresses; + } +**/ +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/Entities.csv b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/Entities.csv new file mode 100644 index 0000000000000000000000000000000000000000..05e2b3d60b4777c3fba93fd852d8733713e328d4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/Entities.csv @@ -0,0 +1,18 @@ +#exerciseID,#siteID,#entityID,#entityKind,#Country,#Domain,#Category,#Subcategory,#special,#lat,#long,Marking +1,1,66,1,225,1,1,1,2,36.5955,-121.875,CoCDR +1,1,65,1,225,1,1,1,2,36.588,-121.882,CoXO +1,1,11,1,225,1,1,1,2,36.596,-121.877,1stPL +1,1,12,1,225,1,1,1,4,36.597,-121.878,1stRoller +1,1,13,1,225,1,1,1,5,36.594,-121.878,1stPlow +1,1,14,1,225,1,1,1,2,36.595,-121.877,1stPSG +1,1,21,1,225,1,1,1,2,36.603,-121.88,2ndPL +1,1,22,1,225,1,1,1,4,36.604,-121.881,2ndRoller +1,1,23,1,225,1,1,1,5,36.601,-121.881,2ndPlow +1,1,24,1,225,1,1,1,2,36.602,-121.88,2ndPSG +1,1,31,1,225,1,1,1,2,36.588,-121.88,3rdPL +1,1,32,1,225,1,1,1,4,36.589,-121.881,3rdRoller +1,1,33,1,225,1,1,1,5,36.586,-121.881,3rdPlow +1,1,34,1,225,1,1,1,2,36.587,-121.88,3rdPSG +1,1,7,1,225,1,6,1,1,36.5956,-121.87701,Co1SG +1,1,4,1,225,1,7,12,1,36.596,-121.878,CoSupSgt +1,1,77,1,225,1,3,14,0,36.595,-121.879,CoEvac diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/HanleyOpenDisEspduSenderFP.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/HanleyOpenDisEspduSenderFP.java new file mode 100644 index 0000000000000000000000000000000000000000..cf08032229642081e99bf53a98451f12a6b71de6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/Hanley/HanleyOpenDisEspduSenderFP.java @@ -0,0 +1,395 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.Hanley; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/**This file reads a .csv and send out ESPDUs based on each row of the .csv. + * This file uses Don McGregors original example of OpneDisEspduSender as the + * starting point for the file and was modified to read the .csv and send an + * espdu for each entry. + * + * modified for MV3500 final project by Brian Hanley + * + * + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class HanleyOpenDisEspduSenderFP +{ + //public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) throws FileNotFoundException +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. +// EntityType entityType = espdu.getEntityType(); +// entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) +// entityType.setCountry(224); // UK +// entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) +// entityType.setCategory((short)1); // Tank +// entityType.setSubcategory((short)1); // M1 Abrams +// entityType.setSpec((short)4); // M1A1 w/ mine roller + + + Set<InetAddress> broadcastAddresses; + // Loop through sending .csv entities + String fileName = "FinalProjects/2018March/Hanley/Entities.csv"; + File inputFile = new File(fileName); + Scanner scanner; + try + { + + ////// + for (int idx =0; idx<10; idx++){ + scanner = new Scanner(inputFile); //this scanner reads from the .csv file identified by fileName + + + //this next line is only necesary if the .csv has a header row. this has the + //scanner read the line and gets ready for the parsing in the while loop. + //if the .csv does not have a header, comment out this line or you will miss the first entity. + scanner.nextLine(); + + //this section reads through the .csv and parses it to send out as an espdu. + while(scanner.hasNextLine()) { + String line = scanner.nextLine(); + //System.out.println(line); + String[] splits; + splits = line.split(","); + if (splits[0].startsWith("#")) continue; + //this section parse each line into the component necessary to build a DIS ESPDU; + int kind = Integer.parseInt(splits[3]); + int country = Integer.parseInt(splits[4]); + int domain = Integer.parseInt(splits[5]); + int category = Integer.parseInt(splits[6]); + int subCategory = Integer.parseInt(splits[7]); + int special = Integer.parseInt(splits[8]); + int bumperNumber = Integer.parseInt(splits[2]); + float entityLat = Float.parseFloat(splits[9]); + //System.out.println(entityLat); + float entityLon = Float.parseFloat(splits[10]); + String marking = splits[11]; + //System.out.println(marking); + + //This section provides the ESPDU its entity specific information + entityID.setEntity(bumperNumber); + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short) kind); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry((short)country); // country identifier from .csv all should be us for this example + entityType.setDomain((short)domain); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)category); // for this exampl tank, light truck, heavy truck or light armor + entityType.setSubcategory((short)subCategory); // M1 Abrams, M113, M998, or FMTV + entityType.setSpec((short)special); // various for this example + //System.out.println("entity ID: "+ bumperNumber); // a check built to make sure each line of the .csv was being read and parsed + Marking entityMarking = new Marking(); //creates a marking instance which can be added to the espdu + entityMarking.setCharactersString(marking); + espdu.setMarking(entityMarking); + + //System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + //for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + //double direction = Math.pow((-1.0), (idx)); + lon = entityLon + (idx * 0.002); + lat = entityLat + (idx * 0.002); + //System.out.println(lat); + //System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + //System.out.println("lat, lon:" + lat + ", " + lon); + //System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + //FirePdu fire = new FirePdu(); + //byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + //System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + // socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + //Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + if (bumperNumber == 66){ + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.printf(" Location (lat/lon/alt): [ %.4f , %.4f, %.4f] \n",lla[0],lla[1],lla[2]); + } + + } + ////// + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + System.out.println("Iteration "+idx); + System.out.println("Sleep Time"); + Thread.sleep(3000); + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/README.md new file mode 100644 index 0000000000000000000000000000000000000000..10a791462038cfa4abdc40d63665eea32fe42645 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/README.md @@ -0,0 +1,46 @@ +MV3500 - Internetwork Communications and Simulation +Prof. Dr. Don Brutzman + +Landas, Enrico +Tacket, Cody +Yamashita de Moura, Douglas + +Final Project +Adapt a Unity or Other Program to Emit PDUs Using Open-DIS C# Binding + +Two C# scripts, Sender.cs and Receiver.cs, were created to send and receive +PDUs, respectively. The following data is included: + +Sender.cs +- IP Address: 239.1.2.3 +- Port: 3000 +- EntityID.Entity: 1 + +Receiver.cs +- IP Address: 239.1.2.3 +- Port: 3000 +- EntityID.Entity to be processed: anyone different from 1 + +For the project purpose, the scripts were implemented in such a way that all +multicast information is enclosed on the scripts and only selected information +is processed and printed on the screen. Each computer will print the data +from the entity that is different from the one it is sending. + +Unity Project +- The Unity package can be downloaded from: +- https://owncloud.nps.edu/owncloud/index.php/s/mewLa2BUEWhucPa + +Video +- A video showing two applications working can be found at the Video folder +of the Unity package + +TO-DO List +- Create an Unity interface to receive input data: IP address, port, etc +- Transform the object location to real world location (using latitude, +longitude and altitude) +- Replace the 'InvokeRepeating' method using a thread (when creating a sender +and a client on the same computer, this method may not work properly, i.e., +the interval between the calls could be different from the expected) +- Implement creation of the received object on the Receiver.cs (or other +interface to be created) +- Implement control of the object (NavySeal guy) using keyboard/mouse \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Receiver.cs b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Receiver.cs new file mode 100644 index 0000000000000000000000000000000000000000..8504e9fd0d29c75f99b2a87d8ad096203150c25d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Receiver.cs @@ -0,0 +1,100 @@ +using System; +using UnityEngine; +using System.Net; +using System.Net.Sockets; +using OpenDis.Core; +using OpenDis.Dis1998; +using OpenDis.Enumerations; +using UnityEngine.UI; + +public class Receiver : MonoBehaviour { + + UdpClient client; + IPEndPoint localEp; + EntityStatePdu newEntityStatePDU; + IPAddress multicastaddress; + PduProcessor pduProcessor; + int PDU_TYPE_POSITION = 2; + public GameObject locationText; + Vector3Double location; + EntityID entityID; + EntityType entityType; + + // Use this for initialization + public void onClick () { + + Debug.Log("Start receiving..."); + + // Create UDP Client to receive data + client = new UdpClient(); + client.ExclusiveAddressUse = false; + localEp = new IPEndPoint(IPAddress.Any, 3000); + client.Client.SetSocketOption(SocketOptionLevel.Socket, + SocketOptionName.ReuseAddress, true); + client.ExclusiveAddressUse = false; + client.Client.Bind(localEp); + multicastaddress = IPAddress.Parse("239.1.2.3"); + client.JoinMulticastGroup(multicastaddress); + locationText = GameObject.FindGameObjectWithTag("ReceiverLocationText"); + + // Broadcast IP - Client + InvokeRepeating("BroadcastClientIP", 0, 1f); + } + + // Receive data + void BroadcastClientIP() + { + try + { + if(client.Available > 0) + { + // Blocks until a message returns on this socket from a remote host. + Byte[] receivedBytes = client.Receive(ref localEp); + + if(receivedBytes != null && receivedBytes.Length > 0) + { + try + { + PduType pduType = (PduType)receivedBytes[PDU_TYPE_POSITION]; + Pdu pdu = PduProcessor.UnmarshalRawPdu(pduType, receivedBytes, Endian.Big); + switch ((PduType)pdu.PduType) + { + case PduType.EntityState: + ProcessEntityStatePdu((EntityStatePdu)pdu); + SetLocationText(); + break; + default: + break; + } + } catch (Exception e) + { + Debug.LogError(e.ToString()); + } + } + } + } + catch (Exception e) + { + Debug.LogError(e.ToString()); + } + } + + // Process Entity State PDU + void ProcessEntityStatePdu(EntityStatePdu espdu) + { + entityID = espdu.EntityID; + entityType = espdu.EntityType; + location = espdu.EntityLocation; + } + + // Print NavySeal info on screen + void SetLocationText() + { + if (entityID.Entity != 1) + { + locationText.GetComponent<Text>().text = String.Format("NAVY SEAL RECEIVER\nID: {0}\nCountry: {1}\nCategory: {2}\nLocation: ({3}, {4}, {5})", entityID.Entity.ToString(), entityType.Country.ToString(), entityType.Category.ToString(), location.X.ToString("F2"), location.Y.ToString("F2"), location.Z.ToString("F2")); + Debug.Log(String.Format("NAVY SEAL RECEIVER\nID: {0}\nCountry: {1}\nCategory: {2}\nLocation: ({3}, {4}, {5})", entityID.Entity.ToString(), entityType.Country.ToString(), entityType.Category.ToString(), location.X.ToString("F2"), location.Y.ToString("F2"), location.Z.ToString("F2"))); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Sender.cs b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Sender.cs new file mode 100644 index 0000000000000000000000000000000000000000..fb98d126cf787192e6fb9640112bd24686d5e8a3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/LandasTackettDeMoura/Sender.cs @@ -0,0 +1,121 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using UnityEngine; +using System.Net; +using System.Net.Sockets; +using System.Text; +using OpenDis.Dis1998; +using OpenDis.Core; +using System.IO; +using System.Threading; +using UnityEngine.UI; + +public class Sender : MonoBehaviour { + + UdpClient sender; + string serverIP; + int broadcastPort = 3000; + IPEndPoint remoteEP; + string data = ""; + public GameObject locationText; + EntityStatePdu espdu; + EntityID entityID; + EntityType entityType; + + //NavySeal object and position + public GameObject NavySeal; + private double x; + private double y; + private double z; + + void Start() { + + // Get Navy Seal object + NavySeal = GameObject.FindGameObjectWithTag("NavySealPrefab"); + + // Create new entity state and set exercise + espdu = new EntityStatePdu(); + espdu.ExerciseID = 1; + + // Create and set entity marking + Marking myMarking = new Marking(); + myMarking.CharacterSet = 1; + String markingTest = "Test"; + myMarking.Characters = Encoding.UTF8.GetBytes(markingTest); + espdu.Marking = myMarking; + + // Get time stamp + espdu.Timestamp = (uint)DateTimeOffset.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; + + // Set entity ID parameters + entityID = espdu.EntityID; + entityID.Site = 1; + entityID.Application = 1; + entityID.Entity = 1; + + // Set entity type parameters + entityType = espdu.EntityType; + entityType.EntityKind = 1; + entityType.Country = 225; + entityType.Domain = 1; + entityType.Category = 1; + entityType.Subcategory = 20; + entityType.Specific = 3; + + locationText = GameObject.FindGameObjectWithTag("SenderLocationText"); + } + + // Use this for initialization + public void onClick () { + Debug.Log("Starting multicasting..."); + + //Create UDP Client for broadcasting the server + sender = new UdpClient(); + IPAddress groupIP = IPAddress.Parse("239.1.2.3"); + sender.JoinMulticastGroup(groupIP); + remoteEP = new IPEndPoint(groupIP, broadcastPort); + + //Broadcast IP - Server + InvokeRepeating("BroadcastServerIP", 0, 1f); + } + + // Prepare and send data + void BroadcastServerIP() + { + // Get and print entity position + x = NavySeal.transform.position.x; + y = NavySeal.transform.position.y; + z = NavySeal.transform.position.z; + //Debug.Log(NavySeal.transform.position); + + // Set entity location + Vector3Double location = espdu.EntityLocation; + location.X = x; + location.Y = y; + location.Z = z; + + // Get time stamp + espdu.Timestamp = (uint)DateTimeOffset.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds; + + //Prepare output + DataOutputStream dos = new DataOutputStream(Endian.Big); + espdu.MarshalAutoLengthSet(dos); + + // Transmit messages + byte[] buffer = dos.ConvertToBytes(); + sender.Send(buffer, buffer.Length, remoteEP); + //Debug.Log(Time.realtimeSinceStartup + ": Sent broadcast data: " + espdu); + + SetLocationText(); + } + + // Print NavySeal info on screen + void SetLocationText() + { + locationText.GetComponent<Text>().text = String.Format("NAVY SEAL SENDER\nID: {0}\nCountry: {1}\nCategory: {2}\nLocation: ({3}, {4}, {5})", entityID.Entity.ToString(), entityType.Country.ToString(), entityType.Category.ToString(), x.ToString("F2"), y.ToString("F2"), z.ToString("F2")); + Debug.Log(String.Format("NAVY SEAL SENDER\nID: {0}\nCountry: {1}\nCategory: {2}\nLocation: ({3}, {4}, {5})", entityID.Entity.ToString(), entityType.Country.ToString(), entityType.Category.ToString(), x.ToString("F2"), y.ToString("F2"), z.ToString("F2"))); + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a704e52cd0e75e5a801b3642b756d0b74085a1da --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/README.md @@ -0,0 +1,7 @@ +## Final Course Projects 2018March + +Create a dedicated subdirectory for each individual or team project. + +Example: `SmithJones` + +See the course syllabus for details on how to document your project. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java new file mode 100644 index 0000000000000000000000000000000000000000..63dc5f9b46e85e15ab674f4120889b9a6a2a0241 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/CSVreaderOpenDisEspduSenderFP.java @@ -0,0 +1,412 @@ +package MV3500Cohort2018JanuaryMarch.FinalProjects.SasalaMaroon; + + + + + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; +import java.io.File; +import java.io.FileNotFoundException; +import java.util.Scanner; + + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/**This file reads a .csv and send out ESPDUs based on each row of the .csv. + * This file uses Don McGregors original example of OpneDisEspduSender as the + * starting point for the file and was modified to read the .csv and send an + * espdu for each entry. + * + * modified for MV3500 final project by Brian Hanley + * + * + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class CSVreaderOpenDisEspduSenderFP +{ + //public static final int NUMBER_TO_SEND = 5000; + public static final int SENDING_PORT = 1414; + public static final int RECEIVING_PORT = 1415; + public static final String DESTINATION_HOST = "localhost"; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) throws FileNotFoundException +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + //MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + + +// Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + //socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + // socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); +// Marking espduMarking = new Marking(); +// espduMarking.setCharactersString(portString);t +// espdu.setMarking(espduMarking); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. +// EntityType entityType = espdu.getEntityType(); +// entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) +// entityType.setCountry(224); // UK +// entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) +// entityType.setCategory((short)1); // Tank +// entityType.setSubcategory((short)1); // M1 Abrams +// entityType.setSpec((short)4); // M1A1 w/ mine roller + + + Set<InetAddress> broadcastAddresses; + // Loop through sending .csv entities + String fileName = "FinalProjects/2018March/SasalaMaroon/Entities.csv"; + File inputFile = new File(fileName); + Scanner scanner; + try + { + DatagramSocket udpSocket = new DatagramSocket(SENDING_PORT); + + for (int idx =0; idx<400; idx++){ + scanner = new Scanner(inputFile); //this scanner reads from the .csv file identified by fileName + + //this next line is only necesary if the .csv has a header row. this has the + //scanner read the line and gets ready for the parsing in the while loop. + //if the .csv does not have a header, comment out this line or you will miss the first entity. + scanner.nextLine(); + + //this section reads through the .csv and parses it to send out as an espdu. + while(scanner.hasNextLine()) { + String line = scanner.nextLine(); + //System.out.println(line); + String[] splits; + splits = line.split(","); + if (splits[0].startsWith("#")) continue; + //this section parse each line into the component necessary to build a DIS ESPDU; + int kind = Integer.parseInt(splits[3]); + int country = Integer.parseInt(splits[4]); + int domain = Integer.parseInt(splits[5]); + int category = Integer.parseInt(splits[6]); + int subCategory = Integer.parseInt(splits[7]); + int special = Integer.parseInt(splits[8]); + int bumperNumber = Integer.parseInt(splits[2]); + float entityLat = Float.parseFloat(splits[9]); + //System.out.println(entityLat); + float entityLon = Float.parseFloat(splits[10]); + String marking = splits[11]; + //System.out.println(marking); + + //This section provides the ESPDU its entity specific information + entityID.setEntity(bumperNumber); + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short) kind); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry((short)country); // country identifier from .csv all should be us for this example + entityType.setDomain((short)domain); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)category); // for this exampl tank, light truck, heavy truck or light armor + entityType.setSubcategory((short)subCategory); // M1 Abrams, M113, M998, or FMTV + entityType.setSpec((short)special); // various for this example + //System.out.println("entity ID: "+ bumperNumber); // a check built to make sure each line of the .csv was being read and parsed + Marking entityMarking = new Marking(); //creates a marking instance which can be added to the espdu + entityMarking.setCharactersString(marking); + espdu.setMarking(entityMarking); + + //System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + //for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + //double direction = Math.pow((-1.0), (idx)); + lon = entityLon + (idx * 0.002); + lat = entityLat + (idx * 0.002); + //System.out.println(lat); + //System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + //System.out.println("lat, lon:" + lat + ", " + lon); + //System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + //FirePdu fire = new FirePdu(); + //byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + + InetAddress destinationAddress = InetAddress.getByName(DESTINATION_HOST); + + + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + //System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, destinationAddress, RECEIVING_PORT ); + + + //socket.send(packet); + udpSocket.send(packet); + // TODO experiment with these! 8) + //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + // socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + //Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + if (bumperNumber ==66){ + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.printf(" Location (lat/lon/alt): [ %.4f , %.4f, %.4f] \n",lla[0],lla[1],lla[2]); + } + + } + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + System.out.println("Iteration "+idx); + System.out.println("Sleep Time"); + Thread.sleep(3000); + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Entities.csv b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Entities.csv new file mode 100644 index 0000000000000000000000000000000000000000..58ff3efa91237e5ea4bcb5a2a1c841bf7fdeaf9d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Entities.csv @@ -0,0 +1,18 @@ +#exerciseID,#siteID,#entityID,#entityKind,#Country,#Domain,#Category,#Subcategory,#special,#lat,#long,Marking +1,1,66,1,225,1,1,1,2,36.5955,-121.875,CoCDR +1,1,65,1,225,1,1,1,2,36.588,-121.882,CoXO +1,1,11,1,225,1,1,1,2,36.596,-121.877,1stPL +1,1,12,1,225,1,1,1,4,36.597,-121.878,1stRoller +1,1,13,1,225,1,1,1,5,36.594,-121.878,1stPlow +1,1,14,1,225,1,1,1,2,36.595,-121.877,1stPSG +1,1,21,1,225,1,1,1,2,36.603,-121.88,2ndPL +1,1,22,1,225,1,1,1,4,36.604,-121.881,2ndRoller +1,1,23,1,225,1,1,1,5,36.601,-121.881,2ndPlow +1,1,24,1,225,1,1,1,2,36.602,-121.88,2ndPSG +1,1,31,1,225,1,1,1,2,36.588,-121.88,3rdPL +1,1,32,1,225,1,1,1,4,36.589,-121.881,3rdRoller +1,1,33,1,225,1,1,1,5,36.586,-121.881,3rdPlow +1,1,34,1,225,2,1,1,2,36.587,-121.88,3rdPSG +1,1,7,2,225,2,6,1,1,36.5956,-121.87701,Co1SG +1,1,4,2,225,2,7,12,1,36.596,-121.878,CoSupSgt +1,1,77,2,225,2,3,14,0,36.595,-121.879,CoEvac \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/constructive.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/constructive.html new file mode 100644 index 0000000000000000000000000000000000000000..bbb010706b4d816bbbf849a22d2a721df8be434e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/constructive.html @@ -0,0 +1,64 @@ + +<html> + <head> + <title>Constructive Entity DIS Placement</title> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <script type="text/javascript" src="scripts/dis.js"></script> + <script data-main="scripts/main" src="scripts/require.js"></script> + </head> + <body onLoad="initialize()"> + + <div> + <h2>Constructive Simulation DIS Entity</H2><p> + + This web page sends Entity State PDUs with the values below. + Fill out the form, and click "Submit." The page will send ESDPUs + with those values to the web server over a websocket, and the server + will transmit them on the local network.<p> + + The Javascript in the web page will send the ESPDUs with the frequency + indicated (in milliseconds). + + </div> + <div id="data"> + + <form id="EspduForm" action="form_action.asp"> + <b>Entity Type Information; Russian T-72 by Default</b><br> + Kind: <input type="text" name="entitykind" id="entitykind" value="1"><br> + Domain: <input type="text" name="domain" id="domain" value="1"><br> + Country <input type="text" name="country" id="country" value="222"><br> + Category<input type="text" name="category" id="category" value="1"><br> + Subcategory<input type="text" name="subcategory" id="subcategory" value="2"><br> + Specific<input type="text" name="specific" id="specific" value="1"><br> + Extra<input type="text" name="extra" id="extra" value="1"><br><br> + + <b>Entity ID site and application</b><br> + Site<input type="text" name="site" id="site" value="48"><br> + Application<input type="text" name="application" id="application" value="23"><br> + <br> + <b>Location</b></br> + Latitude (Decimal degrees):<input type="text" name="latitude" id="latitude" value="36.595"><br> + Longitude<input type="text" name="longitude" id="longitude" value="-121.877"><br> + Altitude (meters)<input type="text" name="altitude" id="altitude" value="10"><br> + +28.425 + <br> + <b>Marking</b> + Marking<input type="text" name="marking" id="marking" value="MyEntity"><br> + <br> + + <br> + <b>Send Frequency </b><br> + Send Frequency (ms)<input type="text" name="sendfrequency" id="sendfrequency" value="5000"><br> + + <input type="button" name="submit" value="Start Sending PDUs" onClick="constructiveSend(this.form)" > +</form> + </div> + + + + <SCRIPT type="text/javascript" src ="scripts/main.js"></SCRIPT> + + </body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/dis.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/dis.js new file mode 100644 index 0000000000000000000000000000000000000000..83d0e716f4d5e1ab8ff391d6d4a73589abd2474e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/dis.js @@ -0,0 +1,13979 @@ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.CoordinateConversion = function() + { + + this.RADIANS_TO_DEGREES = 180.0/Math.PI; + this.DEGREES_TO_RADIANS = Math.PI/180.0; + + this.a = 6378137.0; //semi major axis (WGS 84) + this.b = 6356752.3142; //semi minor axis (WGS 84) + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.CoordinateConversion.prototype.convertDisToLatLongInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared; //second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + var a = 6378137.0; // shorter variable names + var b = 6356752.3142; + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a * a) / Math.sqrt(((a * a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var result = {latitude:answer[0] * this.RADIANS_TO_DEGREES, longitude:answer[1] * this.RADIANS_TO_DEGREES, altitude:answer[2]}; + return result; + + }; + + /** + * Converts lat long and geodetic height (elevation) into DIS XYZ + * This algorithm also uses the WGS84 ellipsoid, though you can change the values + * of a and b for a different ellipsoid. Adapted from Military Handbook 600008 + * @param latLonAlt {lat: lon: alt:} in degrees and meters + * @return {x: y: z:} in meters + */ + dis.CoordinateConversion.prototype.getXYZfromLatLonAltDegrees = function(latLonAlt) + { + var latitudeRadians = latLonAlt.lat * this.DEGREES_TO_RADIANS; + var longtitudeRadians = latLonAlt.lon * this.DEGREES_TO_RADIANS; + + var cosLat = Math.cos(latitudeRadians); + var sinLat = Math.sin(latitudeRadians); + + + var rSubN = (this.a * this.a) / Math.sqrt(((this.a * this.a) * (cosLat * cosLat) + ((this.b * this.b) * (sinLat*sinLat)))); + + var X = (rSubN + latLonAlt.alt) * cosLat * Math.cos(longtitudeRadians); + var Y = (rSubN + latLonAlt.alt) * cosLat * Math.sin(longtitudeRadians); + var Z = ((((this.b * this.b) / (this.a * this.a)) * rSubN) + latLonAlt.alt) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + }; + + exports.CoordinateConversion = dis.CoordinateConversion; +/** + * Obsolete--the code generation now includes methods for accessing bit + * fields such as this. Remains only for backward compatiblity, and I doubt + * anyone is using it. + * + * Some code to extract the entity apperance bit fields.<p> + * + * The entityAppearance field in the espdu is a 32 bit integer. To save + * space, several different fields are contained within it. + * Specifically: + * + * Name bit position Purpose + * ---- ------------ -------- + * Paint 0 0 = uniform color, 1=camo + * Mobility 1 0 = no mobility kill, 1 = mobility kill + * Fire Power 2 0 = no firepower kill, 1 = firepower kill + * Damage 3-4 0=no damange, 1=slight, 2=moderate, 3=destroyed + * Smoke 5-6 0=not smoking, 1=smoke plume, 2=emitting engine smoke, 3=engine smoke + smoke plume + * Trailing effects 7-8 dust cloud, 0=none, 1=small, 2=medium, 3=large + * hatch 9-11 0=NA, 1=hatch closed, 2=popped, 3=popped + person visible, 4=open, 5=open and visible + * head lights 12 0=off, 1=on + * tail light 13 0=off, 1=on + * brake lights 14 0=off, 1=on + * flaming 15 0=none, 1=flames present + * launcher 16 0=not raised, 1=raised + * camo type 17-18 0=desert, 1=winter, 2=forest + * concealed 19 0=not concealed, 1=prepared concealed position (netting, etc) + * frozen status 20 0=not frozen, 1=frozen (in simulation terms) + * power plant 22 0=power plant off 1=on + * state 23 0=active, 1=deactivated + * tent 24 0=not extended 1=extended + * ramp 25 0=not extended, 1=extended + * blackout lights 26 0=off, 1=on + * blackout brake 27 0=off, 1=on + * spot lights 28 0=off, 1=on + * interior lights 29 0=off, 1=on + * unused 30-31 + * + * Typical use: + * + * var entityAppearance = new DisAppearance(espdu.entityAppearance); + * var damage = entityAppearance.getBitfield(3, 4); + * + * This returns the "damage" bitfield in bits 3-4. + * + * var mobility = entityAppearance.getBitfield(1, 1); + * + * Returns the mobility field, 0 = no mobo kill, 1 = mobility kill + * + * @author DMcG + **/ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor. Takes the integer value extracted from the DIS Entity State Field appearance + * + * @param {type} integerValue the entity appearance from the espdu + * @returns {undefined} + */ +dis.DisAppearance = function(integerValue) +{ + this.entityAppearance = integerValue; +} + +/** + * Test code for creating the correct bitmask + * @returns {undefined} + */ +dis.DisAppearance.prototype.getTestMask = function() +{ + mask = 0; + for(var idx = 0; idx < 7; idx++) + { + mask = mask + this.bit_set(mask, idx); + } + + return mask; +}; + +/** + * + * @param {integer} startPosition + * @param {integer} finishPosition + * @returns {integer} + */ +dis.DisAppearance.prototype.getBitField = function(startPosition, finishPosition) +{ + // do some sanity checks + if(startPosition < 0 || startPosition > 31 || finishPosition < 0 || finishPosition > 31 || startPosition > finishPosition) + { + console.log("invalid start or finish for bitfield values: ", startPosition, " ", finishPosition); + return 0; + } + + // Develop the mask. Addition is equivalent to setting multiple bits. + var mask = 0; + for(var idx = startPosition; idx <= finishPosition; idx++) + { + mask = mask + this.bit_set(0, idx); + } + + // do the bitmask + var maskedValue = this.entityAppearance & mask; + // Shift bits to get the normalized value + var fieldValue = maskedValue >>> startPosition; + + return fieldValue; +}; + +/** Set the "bit" position in a number to 1 + * + * @param {integer} num the number whose bit we are setting. Typically zero. + * @param {integer} bit which bit to set + * @return {integer} the number passed in, with the "bit"th bit flipped on. + **/ +dis.DisAppearance.prototype.bit_set = function(num, bit) +{ + return num | 1<<bit; +} + +exports.DisAppearance = dis.DisAppearance; + +//var BigInteger = require('BigInteger'); + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.InputStream = function(binaryData) +{ + this.dataView = new DataView(binaryData, 0); // data, byte offset + this.currentPosition = 0; // ptr to "current" position in array + + dis.InputStream.prototype.readUByte = function() + { + var data = this.dataView.getUint8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readByte = function() + { + var data = this.dataView.getInt8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readUShort = function() + { + var data = this.dataView.getUint16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readShort = function() + { + var data = this.dataView.getInt16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readUInt = function() + { + var data = this.dataView.getUint32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readInt = function() + { + var data = this.dataView.getInt32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + /** Read a long integer. Assumes big endian format. Uses the BigInteger package. */ + dis.InputStream.prototype.readLongInt = function() + { + var data1 = this.dataView.getInt32(this.currentPosition); + var data2 = this.dataView.getInt32(this.currentPosition + 4); + + this.currentPosition = this.currentPosition + 8; + + }; + + dis.InputStream.prototype.readFloat32 = function() + { + var data = this.dataView.getFloat32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readFloat64 = function() + { + var data = this.dataView.getFloat64(this.currentPosition); + this.currentPosition = this.currentPosition + 8; + return data; + }; + + dis.InputStream.prototype.readLong = function() + { + console.log("Problem in dis.InputStream. Javascript cannot natively handle 64 bit ints"); + console.log("Returning 0 from read, which is almost certainly wrong"); + this.currentPosition = this.currentPosition + 8; + return 0; + }; +}; + +exports.InputStream = dis.InputStream; +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * @param binaryDataBuffer ArrayBuffer +*/ +dis.OutputStream = function(binaryDataBuffer) +{ + this.binaryData = binaryDataBuffer; + this.dataView = new DataView(this.binaryData); // data, byte offset + this.currentPosition = 0; // ptr to current position in array + + /** + * Returns a byte array trimmed to the maximum number of bytes written + * to the stream. Eg, if we initialize with a 500 byte bufer, and we + * only write 10 bytes to the output stream, this will return the first + * ten bytes of the array. + * + * @returns {ArrayBuffer} Only the data written + */ + dis.OutputStream.prototype.toByteArray = function() + { + var trimmedData = this.binaryData.slice(0, this.currentPosition); + return trimmedData; + }; + + + dis.OutputStream.prototype.writeUByte = function(userData) + { + this.dataView.setUint8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeByte = function(userData) + { + this.dataView.setInt8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeUShort = function(userData) + { + this.dataView.setUint16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeShort = function(userData) + { + this.dataView.setInt16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeUInt = function(userData) + { + this.dataView.setUint32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeInt = function(userData) + { + this.dataView.setInt32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat32 = function(userData) + { + this.dataView.setFloat32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat64 = function(userData) + { + this.dataView.setFloat64(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 8; + }; + + dis.OutputStream.prototype.writeLong = function(userData) + { + console.log("Problem in dis.outputStream. Javascript cannot natively handle 64 bit ints"); + console.log("writing 0, which is almost certainly wrong"); + this.dataView.setInt32(this.currentPosition, 0); + this.dataView.setInt32(this.currentPosition + 4, 0); + this.currentPosition = this.currentPosition + 8; + }; +}; + +exports.OutputStream = dis.OutputStream; + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + + /** + * The PDU factory is responsible for decoding binary data and turning + * it into the appropriate type of PDU. + * + * The websocket will typically send the web page a IEEE 1278.1 binary + * array of data. It could be any one of dozens of PDUs. The start of + * all PDUs is the same--they have the same header. One of the fields in + * the header is the PduType, an 8 bit integer with a unqiue value for + * each type of PDU. We have to peak at that value, decide what type + * of PDU to create of the binary we have received, and then decode it. + * + * * @DMcG + */ + + dis.PduFactory = function() + { + + }; + + /** + * decode incoming binary data and + * return the correct type of PDU. + * + * @param {type} data the IEEE 1278.1 binary data + * @returns {Pdu} Returns an instance of some PDU, be it espdu, fire, detonation, etc. Exception if PduType not known. + */ + dis.PduFactory.prototype.createPdu = function(data) + { + var asUint8Array = new Uint8Array(data); + var pduType = asUint8Array[2]; + var inputStream = new dis.InputStream(data); + var newPdu = null; + + //try + //{ + switch(pduType) + { + case 1: // entity state PDU + newPdu = new dis.EntityStatePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 2: // Fire + newPdu = new dis.FirePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 3: // detonation + newPdu = new dis.DetonationPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 4: // Collision + newPdu = new dis.CollisionPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 11: // Create entity + newPdu = new dis.CreateEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 12: // Remove entity + newPdu = new dis.RemoveEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 20: // data + newPdu = new dis.DataPdu(); + newPdu.initFromBinary(inputStream); + break; + + default: + throw "PduType: " + pduType + " Unrecognized PDUType. Add PDU in dis.PduFactory."; + } + //} + // This also picks up any errors decoding what we though was a "normal" PDU + //catch(error) + //{ + // newPdu = null; + //} + + return newPdu; + }; + + dis.PduFactory.prototype.getPdusFromBundle = function(data) + { + } + + +exports.PduFactory = dis.PduFactory; +/** + * Sets up a local tangent place (ENU) coordinate system at a given location + * and altitude, and handles conversions between geodetic, ECEF, and local + * tangent plane coordinate systems. + * + * For reference see "Conversion of Geodetic coordinates to the Local + * Tangent Plane", version 2.01, + * http://www.psas.pdx.edu/CoordinateSystem/Latitude_to_LocalTangent.pdf + * + * and "Geodetic Systems", + * http://wiki.gis.com/wiki/index.php/Geodetic_system#From_geodetic_coordinates_to_local_ENU_coordinates + * + * There's also a bunch of ancient code from older versions that someone, somewhere, + * lifted from a military handbook, originally written in C, translated to Java, + * and now translated to Javascript. + * + * Terminology: + * + * ECEF: earth centered, earth fixed coordinate system, same as DIS. Cartesian, + * origin at center of the earth, z through north pole, x out the equator and + * prime meridian, y out equator and 90 deg east. This coordinate system rotates + * with the earth, ie the x axis always points out the prime meridian and equator + * even as the earth rotates. + * + * Geodetic: latitude, longitude, altitude. + * + * WGS84: Shape of the earth, an ellipsoid roughly, with a and b the semimajor and semiminor axes + * + * ENU: East, North, Up: local coordinate system with a given geodetic origin. Tangent + * plane to the earth. + * + * All Errors mine + * + * @DMcG + * + * @param {float} lat latitude in degrees of the origin of the local tangent plane coordinate system + * @param {float} lon longitude, in degrees, of origin + * @param {float} alt altitude, in meters, of the origin of the local tangent plane coordinate system + */ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor, creates an object that can do coordinate systems conversions. + * Takes a geodetic point that is the origin of a tangent plane to the surface + * of the earth. This is useful for doing local simulation work. The local + * coordinate system has postive x east, positive y north, and positive Z up, + * aka an ENU coordinate system. Methods for converting from that coordinate system + * to the DIS (ECEF) coordinate system or geotetic coordinate systems are provided. + * + * @param {type} lat latitude, in degrees, of where the local tangent plane is located + * @param {type} lon longitude, in degrees, of the origin of the local tangent plane + * @param {type} alt altitude, in meters, of the origin of the local tangent plane + * @returns {RangeCoordinates} An object that can do coordinate system conversions + */ +dis.RangeCoordinates = function(lat, lon, alt) +{ + this.RADIANS_PER_DEGREE = 2 * Math.PI / 360.0; + this.DEGREES_PER_RADIAN = 360.0 / (2* Math.PI); + + /** WGS84 semimajor axis (constant) */ + this.a = 6378137.0; + + /** WGS84 semiminor axis (constant) */ + this.b = 6356752.3142; + + /** Ellipsoidal Flatness (constant) */ + this.f = (this.a - this.b) / this.a; // Should be 3.3528107 X 10^-3 + + /** Eccentricity (constant) */ + this.e = Math.sqrt(this.f * (2 - this.f)); // Should be 8.1819191 X 10^-2 + + // The origin of the local, East-North-Up (ENU) coordinate system, in lat/lon degrees and meters. + this.ENUOrigin = {}; + this.ENUOrigin.latitude = lat; + this.ENUOrigin.longitude = lon; + this.ENUOrigin.altitude = alt; + + // Find the origin of the ENU in earth-centered, earth-fixed ECEF aka DIS coordinates + this.ENUOriginInECEF = {}; + this.ENUOriginInECEF = this.latLonAltDegreesToECEF(lat, lon, alt); +}; + + /** Determines N, the distance from a normal plane at the given + * latitude to the Z-axis running through the center of the earth. + * This is NOT the same as the distance to the center of the earth. + * + * @param {float} lambda the latitude, in radians. + * @returns {float} distance in meters from the latitude to the axis of the earth + */ + dis.RangeCoordinates.prototype.N = function(lambda) + { + //N(lambda) = a / sqrt( 1 - e^2 * sin^2(lambda) ) + var val = this.a / Math.sqrt(1- ( Math.pow(this.e, 2) * Math.pow( Math.sin(lambda), 2) ) ); + return val; + }; + + /** + * Converts a latitude, longitude, and altitude object to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {latitude:longitude:altitude:} latLonAlt The lat/lon/alt, in degrees and meters + * @returns {x, y, z} rectilienar coordinates in ECEF, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesObjectToECEF = function(latLonAlt) + { + return this.latLonAltDegreesToECEF(latLonAlt.latitude, latLonAlt.longitude, latLonAlt.altitude); + }; + + /** + * Converts a latitude, longitude, and altitude to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {float} latitude (in radians) + * @param {float} longitude (in radians) + * @param {float} altitude (in meters) + * @returns {x, y, z} rectilienar coordinates in ECEF-r, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltRadiansToECEF = function(latitude, longitude, altitude) + { + /* + // altitude corresponds to h in the paper, lambda to latitude, phi to longitude + var x = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.cos(longitude); + var y = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.sin(longitude); + var z = (altitude + (1 - Math.pow(this.e, 2) ) * this.N(latitude)) * Math.sin(longitude); + + var coordinates = {}; + coordinates.x = x; + coordinates.y = y; + coordinates.z = z; + */ + + var cosLat = Math.cos(latitude); + var sinLat = Math.sin(latitude); + + var rSubN = (this.a*this.a) / Math.sqrt(((this.a*this.a) * (cosLat*cosLat) + ((this.b*this.b) * (sinLat*sinLat)))); + + var X = (rSubN + altitude) * cosLat * Math.cos(longitude); + var Y = (rSubN + altitude) * cosLat * Math.sin(longitude); + var Z = ((((this.b*this.b) / (this.a*this.a)) * rSubN) + altitude) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + + /* + * + * @param {type} latitude in degrees + * @param {type} longitude in degrees + * @param {type} altitude in meters + * @returns {x,y,z} coordinates in ECEF, in meters aka DIS global coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesToECEF = function(latitude, longitude, altitude) + { + return this.latLonAltRadiansToECEF(latitude * this.RADIANS_PER_DEGREE, longitude * this.RADIANS_PER_DEGREE, altitude); + }; + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. (This is + * copied from other sources than those listed above. Seems to work, though.) + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.RangeCoordinates.prototype.ECEFObjectToLatLongAltInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + var a = this.a; // semi major axis (WGS 84) + var b = this.b; //semi minor axis (WGS 84) + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared;//second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a*a) / Math.sqrt(((a*a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var ld = answer[0] * this.DEGREES_PER_RADIAN; + var lnd = answer[1] * this.DEGREES_PER_RADIAN; + var result = {latitude:ld, longitude:lnd, altitude:answer[2]}; + return result; + + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {x:y:z:} ecefPosition ecef position (in meters) + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFObjectToENU = function(ecefPosition) + { + return this.ECEFtoENU(ecefPosition.x, ecefPosition.y, ecefPosition.z); + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {float} X the X coordinate of the ECEF position + * @param {float} Y the Y coordinate + * @param {float} Z the Z coordinate + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFtoENU = function(X, Y, Z) + { + // Origin of ENU tangent plane coordinate system in ECEF coordinate system + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var originLonRadians = this.ENUOrigin.longitude * this.RADIANS_PER_DEGREE; + var originLatRadians = this.ENUOrigin.latitude * this.RADIANS_PER_DEGREE; + + e = -(Math.sin(originLonRadians)) * (X-Xr) + Math.cos(originLonRadians) * (Y-Yr); + n = -(Math.sin(originLatRadians)) * Math.cos(originLonRadians) * (X-Xr) - Math.sin(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.cos(originLatRadians) * (Z-Zr); + u = Math.cos(originLatRadians) * Math.cos(originLonRadians) * (X-Xr) + Math.cos(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.sin(originLatRadians) * (Z-Zr); + + // Local coordinate system x, y, z + return {x:e, y:n, z:u}; + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane object to ECEF, aka DIS coordinates. + * + * @param enuPosition {x:y:z:} local coordinate object + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUObjectToECEF = function(enuPosition) + { + return this.ENUtoECEF(enuPosition.x, enuPosition.y, enuPosition.z); + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane point to ECEF, aka DIS coordinates. + * + * @param localX {float} local coordinate system X + * @param localY {float} local coordinate system Y + * @param localZ {float} local coordinate system Z + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUtoECEF = function(localX, localY, localZ) + { + // ENU local coordinate system origin, in ECEF + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var refLong = this.ENUOrigin.longitude; + var refLat = this.ENUOrigin.latitude; + + /** original code this was copied from + + function [X, Y, Z] = enu2xyz(refLat, refLong, refH, e, n, u) + % Convert east, north, up coordinates (labeled e, n, u) to ECEF + % coordinates. The reference point (phi, lambda, h) must be given. All distances are in metres + + [Xr,Yr,Zr] = llh2xyz(refLat,refLong, refH); % location of reference point + + X = -sin(refLong)*e - cos(refLong)*sin(refLat)*n + cos(refLong)*cos(refLat)*u + Xr; + Y = cos(refLong)*e - sin(refLong)*sin(refLat)*n + cos(refLat)*sin(refLong)*u + Yr; + Z = cos(refLat)*n + sin(refLat)*u + Zr; + */ + + X = -(Math.sin(refLong)) * localX - Math.cos(refLong) * Math.sin(refLat) * localY + Math.cos(refLong) * Math.cos(refLat) * localZ + Xr; + Y = Math.cos(refLong) * localX - Math.sin(refLong) * Math.sin(refLat) * localY + Math.cos(refLat) * Math.sin(refLong) * localZ + Yr; + Z = Math.cos(refLat) * localY + Math.sin(refLat) * localZ + Zr; + + return {x:X, y:Y, z:Z}; + }; + +exports.RangeCoordinates = dis.RangeCoordinates;if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * Utility class that converts between strings and the DIS ESPDU marking + * field. The marking field is 12 bytes long, with the first byte being + * the character set used, and the remaining 11 bytes character codes in + * that character set. This is often used for debugging or "billboard" + * displays in 3D; it's intended for humans. The string character values + * are clamped (or filled) to exactly 11 bytes, so "This is a long string" + * will be clamped to "This is a l" (in charachter codes) and "foo" will + * be filled to "foo\0\0\0\0\0\0\0\0".<p> + * + * It is recommended that only ASCII character set (character set = 1) + * be used. + * + * @returns {undefined} + */ +dis.StringConversion = function() +{ +}; + +/** + * Given a string, returns a DIS marking field. The character set is set to + * 1, for ascii. The length is clamped to 11, and zero-filled if the string + * is shorter than 11. + * + * @returns {array} disMarking field, 12 bytes long, character set = 1 (ascii) in 0, zero-filled to 11 character codes + */ +dis.StringConversion.prototype.StringToDisMarking = function(markingString) +{ + var byteMarking = []; + + // character set 1 = ascii + byteMarking.push(1); + + var markingLength = markingString.length; + + // Clamp it to 11 bytes of character data + if(markingLength > 11) + markingLength = 11; + + // If the string is shorter than 11 bytes, we zero-fill the array + var diff = 11 - markingLength; + + for(var idx = 0; idx < markingLength; idx++) + { + byteMarking.push(markingString.charCodeAt(idx)); + } + + for(var idx = markingLength; idx < 11; idx++) + { + byteMarking.push(0); + } + + return byteMarking; +}; + +/** + * Given a DIS marking field, returns a string. Assumes always ascii. + * + * @param {array} disMarking dis marking field, [0] = character set, the rest character codes + * @returns {string} string equivalent of the marking field + */ +dis.StringConversion.prototype.DisMarkingToString = function(disMarking) +{ + var marking = ""; + + for(var idx = 1; idx < disMarking.length; idx++) + { + marking = marking + String.fromCharCode(disMarking[idx]); + } + + return marking; +}; + +// This is a temporary placeholder until full require.js code +// support is present. +if (typeof exports === "undefined") + exports = {}; + +exports.RangeCoordinates = dis.RangeCoordinates; +exports.InputStream = dis.InputStream; +exports.OutputStream = dis.OutputStream; + +/** + * Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 15; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** type of message being acknowledged */ + this.acknowledgeFlag = 0; + + /** Whether or not the receiving entity was able to comply with the request */ + this.responseFlag = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.AcknowledgePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgePdu = dis.AcknowledgePdu; + +// End of AcknowledgePdu class + +/** + * Section 5.3.12.5: Ack receipt of a start-resume, stop-freeze, create-entity or remove enitty (reliable) pdus. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 55; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** ack flags */ + this.acknowledgeFlag = 0; + + /** response flags */ + this.responseFlag = 0; + + /** Request ID */ + this.requestID = 0; + + dis.AcknowledgeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgeReliablePdu = dis.AcknowledgeReliablePdu; + +// End of AcknowledgeReliablePdu class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamData = function() +{ + /** beam data length */ + this.beamDataLength = 0; + + /** beamIDNumber */ + this.beamIDNumber = 0; + + /** padding */ + this.pad2 = 0; + + /** fundamental data parameters */ + this.fundamentalDataParameters = new dis.AcousticBeamFundamentalParameter(); + + dis.AcousticBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUShort(); + this.beamIDNumber = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.fundamentalDataParameters.initFromBinary(inputStream); + }; + + dis.AcousticBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.pad2); + this.fundamentalDataParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamData = dis.AcousticBeamData; + +// End of AcousticBeamData class + +/** + * Used in UaPdu + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamFundamentalParameter = function() +{ + /** parameter index */ + this.activeEmissionParameterIndex = 0; + + /** scan pattern */ + this.scanPattern = 0; + + /** beam center azimuth */ + this.beamCenterAzimuth = 0; + + /** azimuthal beamwidth */ + this.azimuthalBeamwidth = 0; + + /** beam center */ + this.beamCenterDE = 0; + + /** DE beamwidth (vertical beamwidth) */ + this.deBeamwidth = 0; + + dis.AcousticBeamFundamentalParameter.prototype.initFromBinary = function(inputStream) + { + this.activeEmissionParameterIndex = inputStream.readUShort(); + this.scanPattern = inputStream.readUShort(); + this.beamCenterAzimuth = inputStream.readFloat32(); + this.azimuthalBeamwidth = inputStream.readFloat32(); + this.beamCenterDE = inputStream.readFloat32(); + this.deBeamwidth = inputStream.readFloat32(); + }; + + dis.AcousticBeamFundamentalParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.activeEmissionParameterIndex); + outputStream.writeUShort(this.scanPattern); + outputStream.writeFloat32(this.beamCenterAzimuth); + outputStream.writeFloat32(this.azimuthalBeamwidth); + outputStream.writeFloat32(this.beamCenterDE); + outputStream.writeFloat32(this.deBeamwidth); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamFundamentalParameter = dis.AcousticBeamFundamentalParameter; + +// End of AcousticBeamFundamentalParameter class + +/** + * Section 5.2.35. information about a specific UA emmtter + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitter = function() +{ + /** the system for a particular UA emitter, and an enumeration */ + this.acousticName = 0; + + /** The function of the acoustic system */ + this.function = 0; + + /** The UA emitter identification number relative to a specific system */ + this.acousticIdNumber = 0; + + dis.AcousticEmitter.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.acousticIdNumber = inputStream.readUByte(); + }; + + dis.AcousticEmitter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.acousticIdNumber); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitter = dis.AcousticEmitter; + +// End of AcousticEmitter class + +/** + * 5.3.35: Information about a particular UA emitter shall be represented using an Acoustic Emitter System record. This record shall consist of three fields: Acoustic Name, Function, and Acoustic ID Number + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystem = function() +{ + /** This field shall specify the system for a particular UA emitter. */ + this.acousticName = 0; + + /** This field shall describe the function of the acoustic system. */ + this.acousticFunction = 0; + + /** This field shall specify the UA emitter identification number relative to a specific system. This field shall be represented by an 8-bit unsigned integer. This field allows the differentiation of multiple systems on an entity, even if in some instances two or more of the systems may be identical UA emitter types. Numbering of systems shall begin with the value 1. */ + this.acousticID = 0; + + dis.AcousticEmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.acousticFunction = inputStream.readUByte(); + this.acousticID = inputStream.readUByte(); + }; + + dis.AcousticEmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.acousticFunction); + outputStream.writeUByte(this.acousticID); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystem = dis.AcousticEmitterSystem; + +// End of AcousticEmitterSystem class + +/** + * Used in the UA pdu; ties together an emmitter and a location. This requires manual cleanup; the beam data should not be attached to each emitter system. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystemData = function() +{ + /** Length of emitter system data */ + this.emitterSystemDataLength = 0; + + /** Number of beams */ + this.numberOfBeams = 0; + + /** padding */ + this.pad2 = 0; + + /** This field shall specify the system for a particular UA emitter. */ + this.acousticEmitterSystem = new dis.AcousticEmitterSystem(); + + /** Represents the location wrt the entity */ + this.emitterLocation = new dis.Vector3Float(); + + /** For each beam in numberOfBeams, an emitter system. This is not right--the beam records need to be at the end of the PDU, rather than attached to each system. */ + this.beamRecords = new Array(); + + dis.AcousticEmitterSystemData.prototype.initFromBinary = function(inputStream) + { + this.emitterSystemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.acousticEmitterSystem.initFromBinary(inputStream); + this.emitterLocation.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.AcousticBeamData(); + anX.initFromBinary(inputStream); + this.beamRecords.push(anX); + } + + }; + + dis.AcousticEmitterSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.emitterSystemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.pad2); + this.acousticEmitterSystem.encodeToBinary(outputStream); + this.emitterLocation.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamRecords.length; idx++) + { + beamRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystemData = dis.AcousticEmitterSystemData; + +// End of AcousticEmitterSystemData class + +/** + * Section 5.3.6.6. Request from simulation manager to an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 16; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** identifies the action being requested */ + this.actionID = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestPdu = dis.ActionRequestPdu; + +// End of ActionRequestPdu class + +/** + * Section 5.3.12.6: request from a simulation manager to a managed entity to perform a specified action. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 56; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** request ID */ + this.actionID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionRequestReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionRequestReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestReliablePdu = dis.ActionRequestReliablePdu; + +// End of ActionRequestReliablePdu class + +/** + * Section 5.3.6.7. response to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 17; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** Status of response */ + this.requestStatus = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requestStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.requestStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponsePdu = dis.ActionResponsePdu; + +// End of ActionResponsePdu class + +/** + * Section 5.3.12.7: Response from an entity to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponseReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 57; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** status of response */ + this.responseStatus = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionResponseReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.responseStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionResponseReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.responseStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponseReliablePdu = dis.ActionResponseReliablePdu; + +// End of ActionResponseReliablePdu class + +/** + * Section 5.2.36. Each agregate in a given simulation app is given an aggregate identifier number unique for all other aggregates in that app and in that exercise. The id is valid for the duration of the the exercise. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the aggregate ID */ + this.aggregateID = 0; + + dis.AggregateID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.aggregateID = inputStream.readUShort(); + }; + + dis.AggregateID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.aggregateID); + }; +}; // end of class + + // node.js module support +exports.AggregateID = dis.AggregateID; + +// End of AggregateID class + +/** + * Section 5.2.37. Specifies the character set used inthe first byte, followed by up to 31 characters of text data. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateMarking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.AggregateMarking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 31; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.AggregateMarking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 31; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.AggregateMarking = dis.AggregateMarking; + +// End of AggregateMarking class + +/** + * Section 5.3.9.1 informationa bout aggregating entities anc communicating information about the aggregated entities. requires manual intervention to fix the padding between entityID lists and silent aggregate sysem lists--this padding is dependent on how many entityIDs there are, and needs to be on a 32 bit word boundary. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 33; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.aggregateID = new dis.EntityID(); + + /** force ID */ + this.forceID = 0; + + /** state of aggregate */ + this.aggregateState = 0; + + /** entity type of the aggregated entities */ + this.aggregateType = new dis.EntityType(); + + /** formation of aggregated entities */ + this.formation = 0; + + /** marking for aggregate; first char is charset type, rest is char data */ + this.aggregateMarking = new dis.AggregateMarking(); + + /** dimensions of bounding box for the aggregated entities, origin at the center of mass */ + this.dimensions = new dis.Vector3Float(); + + /** orientation of the bounding box */ + this.orientation = new dis.Orientation(); + + /** center of mass of the aggregation */ + this.centerOfMass = new dis.Vector3Double(); + + /** velocity of aggregation */ + this.velocity = new dis.Vector3Float(); + + /** number of aggregates */ + this.numberOfDisAggregates = 0; + + /** number of entities */ + this.numberOfDisEntities = 0; + + /** number of silent aggregate types */ + this.numberOfSilentAggregateTypes = 0; + + /** number of silent entity types */ + this.numberOfSilentEntityTypes = 0; + + /** aggregates list */ + this.aggregateIDList = new Array(); + + /** entity ID list */ + this.entityIDList = new Array(); + + /** ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed */ + this.pad2 = 0; + + /** silent entity types */ + this.silentAggregateSystemList = new Array(); + + /** silent entity types */ + this.silentEntitySystemList = new Array(); + + /** number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variableDatums */ + this.variableDatumList = new Array(); + + dis.AggregateStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.aggregateID.initFromBinary(inputStream); + this.forceID = inputStream.readUByte(); + this.aggregateState = inputStream.readUByte(); + this.aggregateType.initFromBinary(inputStream); + this.formation = inputStream.readUInt(); + this.aggregateMarking.initFromBinary(inputStream); + this.dimensions.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.centerOfMass.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.numberOfDisAggregates = inputStream.readUShort(); + this.numberOfDisEntities = inputStream.readUShort(); + this.numberOfSilentAggregateTypes = inputStream.readUShort(); + this.numberOfSilentEntityTypes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfDisAggregates; idx++) + { + var anX = new dis.AggregateID(); + anX.initFromBinary(inputStream); + this.aggregateIDList.push(anX); + } + + for(var idx = 0; idx < this.numberOfDisEntities; idx++) + { + var anX = new dis.EntityID(); + anX.initFromBinary(inputStream); + this.entityIDList.push(anX); + } + + this.pad2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfSilentAggregateTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentAggregateSystemList.push(anX); + } + + for(var idx = 0; idx < this.numberOfSilentEntityTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentEntitySystemList.push(anX); + } + + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumList.push(anX); + } + + }; + + dis.AggregateStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.aggregateID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.aggregateState); + this.aggregateType.encodeToBinary(outputStream); + outputStream.writeUInt(this.formation); + this.aggregateMarking.encodeToBinary(outputStream); + this.dimensions.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + this.centerOfMass.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfDisAggregates); + outputStream.writeUShort(this.numberOfDisEntities); + outputStream.writeUShort(this.numberOfSilentAggregateTypes); + outputStream.writeUShort(this.numberOfSilentEntityTypes); + for(var idx = 0; idx < this.aggregateIDList.length; idx++) + { + aggregateIDList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.entityIDList.length; idx++) + { + entityIDList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad2); + for(var idx = 0; idx < this.silentAggregateSystemList.length; idx++) + { + silentAggregateSystemList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.silentEntitySystemList.length; idx++) + { + silentEntitySystemList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.variableDatumList.length; idx++) + { + variableDatumList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AggregateStatePdu = dis.AggregateStatePdu; + +// End of AggregateStatePdu class + +/** + * Section 5.2.38. Identifies the type of aggregate including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateType = function() +{ + /** Kind of entity */ + this.aggregateKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field, sql has a reserved word for specific */ + this.specificInfo = 0; + + this.extra = 0; + + dis.AggregateType.prototype.initFromBinary = function(inputStream) + { + this.aggregateKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specificInfo = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.AggregateType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.aggregateKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specificInfo); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.AggregateType = dis.AggregateType; + +// End of AggregateType class + +/** + * 5.2.2: angular velocity measured in radians per second out each of the entity's own coordinate axes. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AngularVelocityVector = function() +{ + /** velocity about the x axis */ + this.x = 0; + + /** velocity about the y axis */ + this.y = 0; + + /** velocity about the zaxis */ + this.z = 0; + + dis.AngularVelocityVector.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.AngularVelocityVector.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.AngularVelocityVector = dis.AngularVelocityVector; + +// End of AngularVelocityVector class + +/** + * 5.2.3: location of the radiating portion of the antenna, specified in world coordinates and entity coordinates. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AntennaLocation = function() +{ + /** Location of the radiating portion of the antenna in world coordinates */ + this.antennaLocation = new dis.Vector3Double(); + + /** Location of the radiating portion of the antenna in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + dis.AntennaLocation.prototype.initFromBinary = function(inputStream) + { + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + }; + + dis.AntennaLocation.prototype.encodeToBinary = function(outputStream) + { + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AntennaLocation = dis.AntennaLocation; + +// End of AntennaLocation class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ApaData = function() +{ + /** Index of APA parameter */ + this.parameterIndex = 0; + + /** Index of APA parameter */ + this.parameterValue = 0; + + dis.ApaData.prototype.initFromBinary = function(inputStream) + { + this.parameterIndex = inputStream.readUShort(); + this.parameterValue = inputStream.readShort(); + }; + + dis.ApaData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.parameterIndex); + outputStream.writeShort(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ApaData = dis.ApaData; + +// End of ApaData class + +/** + * Section 5.3.11.5: Information about the addition/modification of an oobject that is geometrically achored to the terrain with a set of three or more points that come to a closure. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArealObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 45; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications enumeration */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.EntityType(); + + /** Object appearance */ + this.objectAppearance = new dis.SixByteChunk(); + + /** Number of points */ + this.numberOfPoints = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** location of object */ + this.objectLocation = new Array(); + + dis.ArealObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectAppearance.initFromBinary(inputStream); + this.numberOfPoints = inputStream.readUShort(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPoints; idx++) + { + var anX = new dis.Vector3Double(); + anX.initFromBinary(inputStream); + this.objectLocation.push(anX); + } + + }; + + dis.ArealObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectAppearance.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfPoints); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + for(var idx = 0; idx < this.objectLocation.length; idx++) + { + objectLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ArealObjectStatePdu = dis.ArealObjectStatePdu; + +// End of ArealObjectStatePdu class + +/** + * Section 5.2.5. Articulation parameters for movable parts and attached parts of an entity. Specifes wether or not a change has occured, the part identifcation of the articulated part to which it is attached, and the type and value of each parameter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArticulationParameter = function() +{ + this.parameterTypeDesignator = 0; + + this.changeIndicator = 0; + + this.partAttachedTo = 0; + + this.parameterType = 0; + + this.parameterValue = 0; + + dis.ArticulationParameter.prototype.initFromBinary = function(inputStream) + { + this.parameterTypeDesignator = inputStream.readUByte(); + this.changeIndicator = inputStream.readUByte(); + this.partAttachedTo = inputStream.readUShort(); + this.parameterType = inputStream.readInt(); + this.parameterValue = inputStream.readFloat64(); + }; + + dis.ArticulationParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.parameterTypeDesignator); + outputStream.writeUByte(this.changeIndicator); + outputStream.writeUShort(this.partAttachedTo); + outputStream.writeInt(this.parameterType); + outputStream.writeFloat64(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ArticulationParameter = dis.ArticulationParameter; + +// End of ArticulationParameter class + +/** + * Section 5.2.4.2. Used when the antenna pattern type field has a value of 1. Specifies the direction, patter, and polarization of radiation from an antenna. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamAntennaPattern = function() +{ + /** The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record. */ + this.beamDirection = new dis.Orientation(); + + this.azimuthBeamwidth = 0; + + this.elevationBeamwidth = 0; + + this.referenceSystem = 0; + + this.padding1 = 0; + + this.padding2 = 0; + + /** Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ez = 0; + + /** Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ex = 0; + + /** THe phase angle between Ez and Ex in radians. */ + this.phase = 0; + + dis.BeamAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.beamDirection.initFromBinary(inputStream); + this.azimuthBeamwidth = inputStream.readFloat32(); + this.elevationBeamwidth = inputStream.readFloat32(); + this.referenceSystem = inputStream.readFloat32(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + this.ez = inputStream.readFloat32(); + this.ex = inputStream.readFloat32(); + this.phase = inputStream.readFloat32(); + }; + + dis.BeamAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + this.beamDirection.encodeToBinary(outputStream); + outputStream.writeFloat32(this.azimuthBeamwidth); + outputStream.writeFloat32(this.elevationBeamwidth); + outputStream.writeFloat32(this.referenceSystem); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + outputStream.writeFloat32(this.ez); + outputStream.writeFloat32(this.ex); + outputStream.writeFloat32(this.phase); + }; +}; // end of class + + // node.js module support +exports.BeamAntennaPattern = dis.BeamAntennaPattern; + +// End of BeamAntennaPattern class + +/** + * Section 5.2.39. Specification of the data necessary to describe the scan volume of an emitter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamData = function() +{ + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.BeamData.prototype.initFromBinary = function(inputStream) + { + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.BeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.BeamData = dis.BeamData; + +// End of BeamData class + +/** + * Section 5.2.7. Specifies the type of muntion fired, the type of warhead, the type of fuse, the number of rounds fired, and the rate at which the roudns are fired in rounds per minute. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BurstDescriptor = function() +{ + /** What munition was used in the burst */ + this.munition = new dis.EntityType(); + + /** type of warhead */ + this.warhead = 0; + + /** type of fuse used */ + this.fuse = 0; + + /** how many of the munition were fired */ + this.quantity = 0; + + /** rate at which the munition was fired */ + this.rate = 0; + + dis.BurstDescriptor.prototype.initFromBinary = function(inputStream) + { + this.munition.initFromBinary(inputStream); + this.warhead = inputStream.readUShort(); + this.fuse = inputStream.readUShort(); + this.quantity = inputStream.readUShort(); + this.rate = inputStream.readUShort(); + }; + + dis.BurstDescriptor.prototype.encodeToBinary = function(outputStream) + { + this.munition.encodeToBinary(outputStream); + outputStream.writeUShort(this.warhead); + outputStream.writeUShort(this.fuse); + outputStream.writeUShort(this.quantity); + outputStream.writeUShort(this.rate); + }; +}; // end of class + + // node.js module support +exports.BurstDescriptor = dis.BurstDescriptor; + +// End of BurstDescriptor class + +/** + * Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ClockTime = function() +{ + /** Hours in UTC */ + this.hour = 0; + + /** Time past the hour */ + this.timePastHour = 0; + + dis.ClockTime.prototype.initFromBinary = function(inputStream) + { + this.hour = inputStream.readInt(); + this.timePastHour = inputStream.readUInt(); + }; + + dis.ClockTime.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.hour); + outputStream.writeUInt(this.timePastHour); + }; +}; // end of class + + // node.js module support +exports.ClockTime = dis.ClockTime; + +// End of ClockTime class + +/** + * 5.3.3.3. Information about elastic collisions in a DIS exercise shall be communicated using a Collision-Elastic PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionElasticPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 66; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.collisionEventID = new dis.EventID(); + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.contactVelocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + /** tensor values */ + this.collisionResultXX = 0; + + /** tensor values */ + this.collisionResultXY = 0; + + /** tensor values */ + this.collisionResultXZ = 0; + + /** tensor values */ + this.collisionResultYY = 0; + + /** tensor values */ + this.collisionResultYZ = 0; + + /** tensor values */ + this.collisionResultZZ = 0; + + /** This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates. */ + this.unitSurfaceNormal = new dis.Vector3Float(); + + /** This field shall represent the degree to which energy is conserved in a collision */ + this.coefficientOfRestitution = 0; + + dis.CollisionElasticPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.collisionEventID.initFromBinary(inputStream); + this.pad = inputStream.readShort(); + this.contactVelocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + this.collisionResultXX = inputStream.readFloat32(); + this.collisionResultXY = inputStream.readFloat32(); + this.collisionResultXZ = inputStream.readFloat32(); + this.collisionResultYY = inputStream.readFloat32(); + this.collisionResultYZ = inputStream.readFloat32(); + this.collisionResultZZ = inputStream.readFloat32(); + this.unitSurfaceNormal.initFromBinary(inputStream); + this.coefficientOfRestitution = inputStream.readFloat32(); + }; + + dis.CollisionElasticPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.collisionEventID.encodeToBinary(outputStream); + outputStream.writeShort(this.pad); + this.contactVelocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + outputStream.writeFloat32(this.collisionResultXX); + outputStream.writeFloat32(this.collisionResultXY); + outputStream.writeFloat32(this.collisionResultXZ); + outputStream.writeFloat32(this.collisionResultYY); + outputStream.writeFloat32(this.collisionResultYZ); + outputStream.writeFloat32(this.collisionResultZZ); + this.unitSurfaceNormal.encodeToBinary(outputStream); + outputStream.writeFloat32(this.coefficientOfRestitution); + }; +}; // end of class + + // node.js module support +exports.CollisionElasticPdu = dis.CollisionElasticPdu; + +// End of CollisionElasticPdu class + +/** + * Section 5.3.3.2. Information about a collision. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 4; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** ID of event */ + this.collisionType = 0; + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.velocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + dis.CollisionPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.collisionType = inputStream.readUByte(); + this.pad = inputStream.readByte(); + this.velocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + }; + + dis.CollisionPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.collisionType); + outputStream.writeByte(this.pad); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.CollisionPdu = dis.CollisionPdu; + +// End of CollisionPdu class + +/** + * Section 5.3.6.12. Arbitrary messages can be entered into the data stream via use of this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 22; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.CommentPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.CommentPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentPdu = dis.CommentPdu; + +// End of CommentPdu class + +/** + * Section 5.3.12.12: Arbitrary messages. Only reliable this time. Neds manual intervention to fix padding in variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 62; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.CommentReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.CommentReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentReliablePdu = dis.CommentReliablePdu; + +// End of CommentReliablePdu class + +/** + * Section 5.3.6.1. Create a new entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 11; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.CreateEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityPdu = dis.CreateEntityPdu; + +// End of CreateEntityPdu class + +/** + * Section 5.3.12.1: creation of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 51; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.CreateEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityReliablePdu = dis.CreateEntityReliablePdu; + +// End of CreateEntityReliablePdu class + +/** + * Section 5.3.6.10. Information issued in response to a data query pdu or a set data pdu is communicated using a data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 20; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataPdu = dis.DataPdu; + +// End of DataPdu class + +/** + * Section 5.3.6.8. Request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 18; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** time issues between issues of Data PDUs. Zero means send once only. */ + this.timeInterval = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryPdu = dis.DataQueryPdu; + +// End of DataQueryPdu class + +/** + * Section 5.3.12.8: request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 58; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** time interval between issuing data query PDUs */ + this.timeInterval = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryReliablePdu = dis.DataQueryReliablePdu; + +// End of DataQueryReliablePdu class + +/** + * Section 5.3.12.10: issued in response to a data query R or set dataR pdu. Needs manual intervention to fix padding on variable datums. UNFINSIHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 60; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataReliablePdu = dis.DataReliablePdu; + +// End of DataReliablePdu class + +/** + * represents values used in dead reckoning algorithms + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DeadReckoningParameter = function() +{ + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Linear acceleration of the entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + /** angular velocity of the entity */ + this.entityAngularVelocity = new dis.Vector3Float(); + + dis.DeadReckoningParameter.prototype.initFromBinary = function(inputStream) + { + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.entityLinearAcceleration.initFromBinary(inputStream); + this.entityAngularVelocity.initFromBinary(inputStream); + }; + + dis.DeadReckoningParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + this.entityLinearAcceleration.encodeToBinary(outputStream); + this.entityAngularVelocity.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DeadReckoningParameter = dis.DeadReckoningParameter; + +// End of DeadReckoningParameter class + +/** + * Section 5.3.7.2. Handles designating operations. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DesignatorPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 24; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity designating */ + this.designatingEntityID = new dis.EntityID(); + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.codeName = 0; + + /** ID of the entity being designated */ + this.designatedEntityID = new dis.EntityID(); + + /** This field shall identify the designator code being used by the designating entity */ + this.designatorCode = 0; + + /** This field shall identify the designator output power in watts */ + this.designatorPower = 0; + + /** This field shall identify the designator wavelength in units of microns */ + this.designatorWavelength = 0; + + /** designtor spot wrt the designated entity */ + this.designatorSpotWrtDesignated = new dis.Vector3Float(); + + /** designtor spot wrt the designated entity */ + this.designatorSpotLocation = new dis.Vector3Double(); + + /** Dead reckoning algorithm */ + this.deadReckoningAlgorithm = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** linear accelleration of entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + dis.DesignatorPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.designatingEntityID.initFromBinary(inputStream); + this.codeName = inputStream.readUShort(); + this.designatedEntityID.initFromBinary(inputStream); + this.designatorCode = inputStream.readUShort(); + this.designatorPower = inputStream.readFloat32(); + this.designatorWavelength = inputStream.readFloat32(); + this.designatorSpotWrtDesignated.initFromBinary(inputStream); + this.designatorSpotLocation.initFromBinary(inputStream); + this.deadReckoningAlgorithm = inputStream.readByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readByte(); + this.entityLinearAcceleration.initFromBinary(inputStream); + }; + + dis.DesignatorPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.designatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.codeName); + this.designatedEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.designatorCode); + outputStream.writeFloat32(this.designatorPower); + outputStream.writeFloat32(this.designatorWavelength); + this.designatorSpotWrtDesignated.encodeToBinary(outputStream); + this.designatorSpotLocation.encodeToBinary(outputStream); + outputStream.writeByte(this.deadReckoningAlgorithm); + outputStream.writeUShort(this.padding1); + outputStream.writeByte(this.padding2); + this.entityLinearAcceleration.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DesignatorPdu = dis.DesignatorPdu; + +// End of DesignatorPdu class + +/** + * Section 5.3.4.2. Information about stuff exploding. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DetonationPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 3; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of muntion that was fired */ + this.munitionID = new dis.EntityID(); + + /** ID firing event */ + this.eventID = new dis.EventID(); + + /** ID firing event */ + this.velocity = new dis.Vector3Float(); + + /** where the detonation is, in world coordinates */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munition used */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** location of the detonation or impact in the target entity's coordinate system. This information should be used for damage assessment. */ + this.locationInEntityCoordinates = new dis.Vector3Float(); + + /** result of the explosion */ + this.detonationResult = 0; + + /** How many articulation parameters we have */ + this.numberOfArticulationParameters = 0; + + /** padding */ + this.pad = 0; + + this.articulationParameters = new Array(); + + dis.DetonationPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.locationInEntityCoordinates.initFromBinary(inputStream); + this.detonationResult = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.pad = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.DetonationPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.locationInEntityCoordinates.encodeToBinary(outputStream); + outputStream.writeUByte(this.detonationResult); + outputStream.writeUByte(this.numberOfArticulationParameters); + outputStream.writeShort(this.pad); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DetonationPdu = dis.DetonationPdu; + +// End of DetonationPdu class + +/** + * Section 5.3.7. Electronic Emissions. Abstract superclass for distirubted emissions PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DistributedEmissionsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.DistributedEmissionsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.DistributedEmissionsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.DistributedEmissionsFamilyPdu = dis.DistributedEmissionsFamilyPdu; + +// End of DistributedEmissionsFamilyPdu class + +/** + * 64 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EightByteChunk = function() +{ + /** Eight bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0); + + dis.EightByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 8; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.EightByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 8; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.EightByteChunk = dis.EightByteChunk; + +// End of EightByteChunk class + +/** + * Description of one electronic emission beam + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionBeamData = function() +{ + /** This field shall specify the length of this beams data in 32 bit words */ + this.beamDataLength = 0; + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.beamIDNumber = 0; + + /** This field shall specify a Beam Parameter Index number that shall be used by receiving entities in conjunction with the Emitter Name field to provide a pointer to the stored database parameters required to regenerate the beam. */ + this.beamParameterIndex = 0; + + /** Fundamental parameter data such as frequency range, beam sweep, etc. */ + this.fundamentalParameterData = new dis.FundamentalParameterData(); + + /** beam function of a particular beam */ + this.beamFunction = 0; + + /** Number of track/jam targets */ + this.numberOfTrackJamTargets = 0; + + /** wheher or not the receiving simulation apps can assume all the targets in the scan pattern are being tracked/jammed */ + this.highDensityTrackJam = 0; + + /** padding */ + this.pad4 = 0; + + /** identify jamming techniques used */ + this.jammingModeSequence = 0; + + /** variable length variablelist of track/jam targets */ + this.trackJamTargets = new Array(); + + dis.ElectronicEmissionBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUByte(); + this.beamIDNumber = inputStream.readUByte(); + this.beamParameterIndex = inputStream.readUShort(); + this.fundamentalParameterData.initFromBinary(inputStream); + this.beamFunction = inputStream.readUByte(); + this.numberOfTrackJamTargets = inputStream.readUByte(); + this.highDensityTrackJam = inputStream.readUByte(); + this.pad4 = inputStream.readUByte(); + this.jammingModeSequence = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfTrackJamTargets; idx++) + { + var anX = new dis.TrackJamTarget(); + anX.initFromBinary(inputStream); + this.trackJamTargets.push(anX); + } + + }; + + dis.ElectronicEmissionBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.beamParameterIndex); + this.fundamentalParameterData.encodeToBinary(outputStream); + outputStream.writeUByte(this.beamFunction); + outputStream.writeUByte(this.numberOfTrackJamTargets); + outputStream.writeUByte(this.highDensityTrackJam); + outputStream.writeUByte(this.pad4); + outputStream.writeUInt(this.jammingModeSequence); + for(var idx = 0; idx < this.trackJamTargets.length; idx++) + { + trackJamTargets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionBeamData = dis.ElectronicEmissionBeamData; + +// End of ElectronicEmissionBeamData class + +/** + * Data about one electronic system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionSystemData = function() +{ + /** This field shall specify the length of this emitter system�s data (including beam data and its track/jam information) in 32-bit words. The length shall include the System Data Length field. */ + this.systemDataLength = 0; + + /** This field shall specify the number of beams being described in the current PDU for the system being described. */ + this.numberOfBeams = 0; + + /** padding. */ + this.emissionsPadding2 = 0; + + /** This field shall specify information about a particular emitter system */ + this.emitterSystem = new dis.EmitterSystem(); + + /** Location with respect to the entity */ + this.location = new dis.Vector3Float(); + + /** variable length variablelist of beam data records */ + this.beamDataRecords = new Array(); + + dis.ElectronicEmissionSystemData.prototype.initFromBinary = function(inputStream) + { + this.systemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.emissionsPadding2 = inputStream.readUShort(); + this.emitterSystem.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.ElectronicEmissionBeamData(); + anX.initFromBinary(inputStream); + this.beamDataRecords.push(anX); + } + + }; + + dis.ElectronicEmissionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.emissionsPadding2); + this.emitterSystem.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamDataRecords.length; idx++) + { + beamDataRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionSystemData = dis.ElectronicEmissionSystemData; + +// End of ElectronicEmissionSystemData class + +/** + * Section 5.3.7.1. Information about active electronic warfare (EW) emissions and active EW countermeasures shall be communicated using an Electromagnetic Emission PDU. COMPLETE (I think) + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionsPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 23; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity emitting */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)]. */ + this.stateUpdateIndicator = 0; + + /** This field shall specify the number of emission systems being described in the current PDU. */ + this.numberOfSystems = 0; + + /** padding */ + this.paddingForEmissionsPdu = 0; + + /** Electronic emmissions systems */ + this.systems = new Array(); + + dis.ElectronicEmissionsPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateUpdateIndicator = inputStream.readUByte(); + this.numberOfSystems = inputStream.readUByte(); + this.paddingForEmissionsPdu = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfSystems; idx++) + { + var anX = new dis.ElectronicEmissionSystemData(); + anX.initFromBinary(inputStream); + this.systems.push(anX); + } + + }; + + dis.ElectronicEmissionsPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.stateUpdateIndicator); + outputStream.writeUByte(this.numberOfSystems); + outputStream.writeUShort(this.paddingForEmissionsPdu); + for(var idx = 0; idx < this.systems.length; idx++) + { + systems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionsPdu = dis.ElectronicEmissionsPdu; + +// End of ElectronicEmissionsPdu class + +/** + * Section 5.2.11. This field shall specify information about a particular emitter system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EmitterSystem = function() +{ + /** Name of the emitter, 16 bit enumeration */ + this.emitterName = 0; + + /** function of the emitter, 8 bit enumeration */ + this.function = 0; + + /** emitter ID, 8 bit enumeration */ + this.emitterIdNumber = 0; + + dis.EmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.emitterName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.emitterIdNumber = inputStream.readUByte(); + }; + + dis.EmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.emitterName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.emitterIdNumber); + }; +}; // end of class + + // node.js module support +exports.EmitterSystem = dis.EmitterSystem; + +// End of EmitterSystem class + +/** + * Each entity in a given DIS simulation application shall be given an entity identifier number unique to all other entities in that application. This identifier number is valid for the duration of the exercise; however, entity identifier numbers may be reused when all possible numbers have been exhausted. No entity shall have an entity identifier number of NO_ENTITY, ALL_ENTITIES, or RQST_ASSIGN_ID. The entity iden- tifier number need not be registered or retained for future exercises. The entity identifier number shall be specified by a 16-bit unsigned integer. An entity identifier number equal to zero with valid site and application identification shall address a simulation application. An entity identifier number equal to ALL_ENTITIES shall mean all entities within the specified site and application. An entity identifier number equal to RQST_ASSIGN_ID allows the receiver of the create entity to define the entity identifier number of the new entity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + dis.EntityID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + }; + + dis.EntityID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + }; +}; // end of class + + // node.js module support +exports.EntityID = dis.EntityID; + +// End of EntityID class + +/** + * Section 5.3.3. Common superclass for EntityState, Collision, collision-elastic, and entity state update PDUs. This should be abstract. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityInformationFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityInformationFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityInformationFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityInformationFamilyPdu = dis.EntityInformationFamilyPdu; + +// End of EntityInformationFamilyPdu class + +/** + * Section 5.3.9. Common superclass for EntityManagment PDUs, including aggregate state, isGroupOf, TransferControLRequest, and isPartOf + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityManagementFamilyPdu = dis.EntityManagementFamilyPdu; + +// End of EntityManagementFamilyPdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Unique ID for an entity that is tied to this state information */ + this.entityID = new dis.EntityID(); + + /** What force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the type of entity in the world */ + this.entityType = new dis.EntityType(); + + this.alternativeEntityType = new dis.EntityType(); + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** parameters used for dead reckoning */ + this.deadReckoningParameters = new dis.DeadReckoningParameter(); + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new dis.Marking(); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.EntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityType.initFromBinary(inputStream); + this.alternativeEntityType.initFromBinary(inputStream); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningParameters.initFromBinary(inputStream); + this.marking.initFromBinary(inputStream); + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + this.entityType.encodeToBinary(outputStream); + this.alternativeEntityType.encodeToBinary(outputStream); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + this.deadReckoningParameters.encodeToBinary(outputStream); + this.marking.encodeToBinary(outputStream); + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStatePdu = dis.EntityStatePdu; + +// End of EntityStatePdu class + +/** + * 5.3.3.4. Nonstatic information about a particular entity may be communicated by issuing an Entity State Update PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStateUpdatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 67; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** This field shall identify the entity issuing the PDU */ + this.entityID = new dis.EntityID(); + + /** Padding */ + this.padding1 = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + this.articulationParameters = new Array(); + + dis.EntityStateUpdatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.padding1 = inputStream.readByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStateUpdatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeByte(this.padding1); + outputStream.writeUByte(this.numberOfArticulationParameters); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStateUpdatePdu = dis.EntityStateUpdatePdu; + +// End of EntityStateUpdatePdu class + +/** + * Section 5.2.16. Identifies the type of entity, including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Renamed from specific because that is a reserved word in SQL */ + this.spec = 0; + + this.extra = 0; + + dis.EntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.spec = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.EntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.spec); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.EntityType = dis.EntityType; + +// End of EntityType class + +/** + * Section 5.2.40. Information about a geometry, a state associated with a geometry, a bounding volume, or an associated entity ID. NOTE: this class requires hand coding. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Environment = function() +{ + /** Record type */ + this.environmentType = 0; + + /** length, in bits */ + this.length = 0; + + /** Identify the sequentially numbered record index */ + this.recordIndex = 0; + + /** padding */ + this.padding1 = 0; + + /** Geometry or state record */ + this.geometry = 0; + + /** padding to bring the total size up to a 64 bit boundry */ + this.padding2 = 0; + + dis.Environment.prototype.initFromBinary = function(inputStream) + { + this.environmentType = inputStream.readUInt(); + this.length = inputStream.readUByte(); + this.recordIndex = inputStream.readUByte(); + this.padding1 = inputStream.readUByte(); + this.geometry = inputStream.readUByte(); + this.padding2 = inputStream.readUByte(); + }; + + dis.Environment.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.environmentType); + outputStream.writeUByte(this.length); + outputStream.writeUByte(this.recordIndex); + outputStream.writeUByte(this.padding1); + outputStream.writeUByte(this.geometry); + outputStream.writeUByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.Environment = dis.Environment; + +// End of Environment class + +/** + * Section 5.3.11.1: Information about environmental effects and processes. This requires manual cleanup. the environmental record is variable, as is the padding. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EnvironmentalProcessPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 41; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Environmental process ID */ + this.environementalProcessID = new dis.EntityID(); + + /** Environment type */ + this.environmentType = new dis.EntityType(); + + /** model type */ + this.modelType = 0; + + /** Environment status */ + this.environmentStatus = 0; + + /** number of environment records */ + this.numberOfEnvironmentRecords = 0; + + /** PDU sequence number for the environmentla process if pdu sequencing required */ + this.sequenceNumber = 0; + + /** environemt records */ + this.environmentRecords = new Array(); + + dis.EnvironmentalProcessPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environementalProcessID.initFromBinary(inputStream); + this.environmentType.initFromBinary(inputStream); + this.modelType = inputStream.readUByte(); + this.environmentStatus = inputStream.readUByte(); + this.numberOfEnvironmentRecords = inputStream.readUByte(); + this.sequenceNumber = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfEnvironmentRecords; idx++) + { + var anX = new dis.Environment(); + anX.initFromBinary(inputStream); + this.environmentRecords.push(anX); + } + + }; + + dis.EnvironmentalProcessPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environementalProcessID.encodeToBinary(outputStream); + this.environmentType.encodeToBinary(outputStream); + outputStream.writeUByte(this.modelType); + outputStream.writeUByte(this.environmentStatus); + outputStream.writeUByte(this.numberOfEnvironmentRecords); + outputStream.writeUShort(this.sequenceNumber); + for(var idx = 0; idx < this.environmentRecords.length; idx++) + { + environmentRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EnvironmentalProcessPdu = dis.EnvironmentalProcessPdu; + +// End of EnvironmentalProcessPdu class + +/** + * Section 5.2.18. Identifies a unique event in a simulation via the combination of three values + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the number of the event */ + this.eventNumber = 0; + + dis.EventID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.eventNumber = inputStream.readUShort(); + }; + + dis.EventID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.eventNumber); + }; +}; // end of class + + // node.js module support +exports.EventID = dis.EventID; + +// End of EventID class + +/** + * Section 5.3.6.11. Reports occurance of a significant event to the simulation manager. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 21; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Type of event */ + this.eventType = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.EventReportPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.EventReportPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.eventType); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportPdu = dis.EventReportPdu; + +// End of EventReportPdu class + +/** + * Section 5.3.12.11: reports the occurance of a significatnt event to the simulation manager. Needs manual intervention to fix padding in variable datums. UNFINISHED. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 61; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Event type */ + this.eventType = 0; + + /** padding */ + this.pad1 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.EventReportReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.EventReportReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.pad1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportReliablePdu = dis.EventReportReliablePdu; + +// End of EventReportReliablePdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. This is identical in function to entity state pdu, but generates less garbage to collect in the Java world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FastEntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + /** what force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Name changed from specific because that is a reserved word in SQL. */ + this.specif = 0; + + this.extra = 0; + + /** Kind of entity */ + this.altEntityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.altDomain = 0; + + /** country to which the design of the entity is attributed */ + this.altCountry = 0; + + /** category of entity */ + this.altCategory = 0; + + /** subcategory of entity */ + this.altSubcategory = 0; + + /** specific info based on subcategory field */ + this.altSpecific = 0; + + this.altExtra = 0; + + /** X velo */ + this.xVelocity = 0; + + /** y Value */ + this.yVelocity = 0; + + /** Z value */ + this.zVelocity = 0; + + /** X value */ + this.xLocation = 0; + + /** y Value */ + this.yLocation = 0; + + /** Z value */ + this.zLocation = 0; + + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** X value */ + this.xAcceleration = 0; + + /** y Value */ + this.yAcceleration = 0; + + /** Z value */ + this.zAcceleration = 0; + + /** X value */ + this.xAngularVelocity = 0; + + /** y Value */ + this.yAngularVelocity = 0; + + /** Z value */ + this.zAngularVelocity = 0; + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.FastEntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specif = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + this.altEntityKind = inputStream.readUByte(); + this.altDomain = inputStream.readUByte(); + this.altCountry = inputStream.readUShort(); + this.altCategory = inputStream.readUByte(); + this.altSubcategory = inputStream.readUByte(); + this.altSpecific = inputStream.readUByte(); + this.altExtra = inputStream.readUByte(); + this.xVelocity = inputStream.readFloat32(); + this.yVelocity = inputStream.readFloat32(); + this.zVelocity = inputStream.readFloat32(); + this.xLocation = inputStream.readFloat64(); + this.yLocation = inputStream.readFloat64(); + this.zLocation = inputStream.readFloat64(); + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.xAcceleration = inputStream.readFloat32(); + this.yAcceleration = inputStream.readFloat32(); + this.zAcceleration = inputStream.readFloat32(); + this.xAngularVelocity = inputStream.readFloat32(); + this.yAngularVelocity = inputStream.readFloat32(); + this.zAngularVelocity = inputStream.readFloat32(); + for(var idx = 0; idx < 12; idx++) + { + this.marking[ idx ] = inputStream.readByte(); + } + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.FastEntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specif); + outputStream.writeUByte(this.extra); + outputStream.writeUByte(this.altEntityKind); + outputStream.writeUByte(this.altDomain); + outputStream.writeUShort(this.altCountry); + outputStream.writeUByte(this.altCategory); + outputStream.writeUByte(this.altSubcategory); + outputStream.writeUByte(this.altSpecific); + outputStream.writeUByte(this.altExtra); + outputStream.writeFloat32(this.xVelocity); + outputStream.writeFloat32(this.yVelocity); + outputStream.writeFloat32(this.zVelocity); + outputStream.writeFloat64(this.xLocation); + outputStream.writeFloat64(this.yLocation); + outputStream.writeFloat64(this.zLocation); + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + outputStream.writeInt(this.entityAppearance); + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + outputStream.writeFloat32(this.xAcceleration); + outputStream.writeFloat32(this.yAcceleration); + outputStream.writeFloat32(this.zAcceleration); + outputStream.writeFloat32(this.xAngularVelocity); + outputStream.writeFloat32(this.yAngularVelocity); + outputStream.writeFloat32(this.zAngularVelocity); + for(var idx = 0; idx < 12; idx++) + { + outputStream.writeByte(this.marking[ idx ] ); + } + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.FastEntityStatePdu = dis.FastEntityStatePdu; + +// End of FastEntityStatePdu class + +/** + * Sectioin 5.3.4.1. Information about someone firing something. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FirePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 2; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of the munition that is being shot */ + this.munitionID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + this.fireMissionIndex = 0; + + /** location of the firing event */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munitions used in the firing event */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** Velocity of the ammunition */ + this.velocity = new dis.Vector3Float(); + + /** range to the target. Note the word range is a SQL reserved word. */ + this.rangeToTarget = 0; + + dis.FirePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.fireMissionIndex = inputStream.readInt(); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.rangeToTarget = inputStream.readFloat32(); + }; + + dis.FirePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeInt(this.fireMissionIndex); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.rangeToTarget); + }; +}; // end of class + + // node.js module support +exports.FirePdu = dis.FirePdu; + +// End of FirePdu class + +/** + * Section 5.2.18. Fixed Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FixedDatum = function() +{ + /** ID of the fixed datum */ + this.fixedDatumID = 0; + + /** Value for the fixed datum */ + this.fixedDatumValue = 0; + + dis.FixedDatum.prototype.initFromBinary = function(inputStream) + { + this.fixedDatumID = inputStream.readUInt(); + this.fixedDatumValue = inputStream.readUInt(); + }; + + dis.FixedDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.fixedDatumID); + outputStream.writeUInt(this.fixedDatumValue); + }; +}; // end of class + + // node.js module support +exports.FixedDatum = dis.FixedDatum; + +// End of FixedDatum class + +/** + * 32 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FourByteChunk = function() +{ + /** four bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0); + + dis.FourByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 4; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.FourByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 4; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.FourByteChunk = dis.FourByteChunk; + +// End of FourByteChunk class + +/** + * Section 5.2.22. Contains electromagnetic emmision regineratin parameters that are variable throughout a scenario dependent on the actions of the participants in the simulation. Also provides basic parametric data that may be used to support low-fidelity simulations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterData = function() +{ + /** center frequency of the emission in hertz. */ + this.frequency = 0; + + /** Bandwidth of the frequencies corresponding to the fequency field. */ + this.frequencyRange = 0; + + /** Effective radiated power for the emission in DdBm. For a radar noise jammer, indicates the peak of the transmitted power. */ + this.effectiveRadiatedPower = 0; + + /** Average repetition frequency of the emission in hertz. */ + this.pulseRepetitionFrequency = 0; + + /** Average pulse width of the emission in microseconds. */ + this.pulseWidth = 0; + + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.FundamentalParameterData.prototype.initFromBinary = function(inputStream) + { + this.frequency = inputStream.readFloat32(); + this.frequencyRange = inputStream.readFloat32(); + this.effectiveRadiatedPower = inputStream.readFloat32(); + this.pulseRepetitionFrequency = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.FundamentalParameterData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.frequencyRange); + outputStream.writeFloat32(this.effectiveRadiatedPower); + outputStream.writeFloat32(this.pulseRepetitionFrequency); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterData = dis.FundamentalParameterData; + +// End of FundamentalParameterData class + +/** + * 5.2.45. Fundamental IFF atc data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterDataIff = function() +{ + /** ERP */ + this.erp = 0; + + /** frequency */ + this.frequency = 0; + + /** pgrf */ + this.pgrf = 0; + + /** Pulse width */ + this.pulseWidth = 0; + + /** Burst length */ + this.burstLength = 0; + + /** Applicable modes enumeration */ + this.applicableModes = 0; + + /** padding */ + this.pad2 = 0; + + /** padding */ + this.pad3 = 0; + + dis.FundamentalParameterDataIff.prototype.initFromBinary = function(inputStream) + { + this.erp = inputStream.readFloat32(); + this.frequency = inputStream.readFloat32(); + this.pgrf = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.burstLength = inputStream.readUInt(); + this.applicableModes = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.pad3 = inputStream.readUByte(); + }; + + dis.FundamentalParameterDataIff.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.erp); + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.pgrf); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeUInt(this.burstLength); + outputStream.writeUByte(this.applicableModes); + outputStream.writeUShort(this.pad2); + outputStream.writeUByte(this.pad3); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterDataIff = dis.FundamentalParameterDataIff; + +// End of FundamentalParameterDataIff class + +/** + * 5.2.44: Grid data record, a common abstract superclass for several subtypes + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecord = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + dis.GridAxisRecord.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + }; + + dis.GridAxisRecord.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + }; +}; // end of class + + // node.js module support +exports.GridAxisRecord = dis.GridAxisRecord; + +// End of GridAxisRecord class + +/** + * 5.2.44: Grid data record, representation 0 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation0 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of bytes of environmental state data */ + this.numberOfBytes = 0; + + /** variable length variablelist of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation0.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfBytes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfBytes; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation0.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfBytes); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation0 = dis.GridAxisRecordRepresentation0; + +// End of GridAxisRecordRepresentation0 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation1 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** constant scale factor */ + this.fieldScale = 0; + + /** constant offset used to scale grid data */ + this.fieldOffset = 0; + + /** Number of data values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation1.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.fieldScale = inputStream.readFloat32(); + this.fieldOffset = inputStream.readFloat32(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation1.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeFloat32(this.fieldScale); + outputStream.writeFloat32(this.fieldOffset); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation1 = dis.GridAxisRecordRepresentation1; + +// End of GridAxisRecordRepresentation1 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation2 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation2.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation2.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation2 = dis.GridAxisRecordRepresentation2; + +// End of GridAxisRecordRepresentation2 class + +/** + * Section 5.3.11.2: Information about globat, spatially varying enviornmental effects. This requires manual cleanup; the grid axis records are variable sized. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GriddedDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 42; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** environmental simulation application ID */ + this.environmentalSimulationApplicationID = new dis.EntityID(); + + /** unique identifier for each piece of enviornmental data */ + this.fieldNumber = 0; + + /** sequence number for the total set of PDUS used to transmit the data */ + this.pduNumber = 0; + + /** Total number of PDUS used to transmit the data */ + this.pduTotal = 0; + + /** coordinate system of the grid */ + this.coordinateSystem = 0; + + /** number of grid axes for the environmental data */ + this.numberOfGridAxes = 0; + + /** are domain grid axes identidal to those of the priveious domain update? */ + this.constantGrid = 0; + + /** type of environment */ + this.environmentType = new dis.EntityType(); + + /** orientation of the data grid */ + this.orientation = new dis.Orientation(); + + /** valid time of the enviormental data sample, 64 bit unsigned int */ + this.sampleTime = 0; + + /** total number of all data values for all pdus for an environmental sample */ + this.totalValues = 0; + + /** total number of data values at each grid point. */ + this.vectorDimension = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** Grid data ^^^This is wrong */ + this.gridDataList = new Array(); + + dis.GriddedDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environmentalSimulationApplicationID.initFromBinary(inputStream); + this.fieldNumber = inputStream.readUShort(); + this.pduNumber = inputStream.readUShort(); + this.pduTotal = inputStream.readUShort(); + this.coordinateSystem = inputStream.readUShort(); + this.numberOfGridAxes = inputStream.readUByte(); + this.constantGrid = inputStream.readUByte(); + this.environmentType.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.sampleTime = inputStream.readLong(); + this.totalValues = inputStream.readUInt(); + this.vectorDimension = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfGridAxes; idx++) + { + var anX = new dis.GridAxisRecord(); + anX.initFromBinary(inputStream); + this.gridDataList.push(anX); + } + + }; + + dis.GriddedDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environmentalSimulationApplicationID.encodeToBinary(outputStream); + outputStream.writeUShort(this.fieldNumber); + outputStream.writeUShort(this.pduNumber); + outputStream.writeUShort(this.pduTotal); + outputStream.writeUShort(this.coordinateSystem); + outputStream.writeUByte(this.numberOfGridAxes); + outputStream.writeUByte(this.constantGrid); + this.environmentType.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeLong(this.sampleTime); + outputStream.writeUInt(this.totalValues); + outputStream.writeUByte(this.vectorDimension); + outputStream.writeUShort(this.padding1); + outputStream.writeUByte(this.padding2); + for(var idx = 0; idx < this.gridDataList.length; idx++) + { + gridDataList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GriddedDataPdu = dis.GriddedDataPdu; + +// End of GriddedDataPdu class + +/** + * 5.3.7.4.1: Navigational and IFF PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer1Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + dis.IffAtcNavAidsLayer1Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + }; + + dis.IffAtcNavAidsLayer1Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer1Pdu = dis.IffAtcNavAidsLayer1Pdu; + +// End of IffAtcNavAidsLayer1Pdu class + +/** + * Section 5.3.7.4.2 When present, layer 2 should follow layer 1 and have the following fields. This requires manual cleanup. the beamData attribute semantics are used in multiple ways. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer2Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + /** layer header */ + this.layerHeader = new dis.LayerHeader(); + + /** beam data */ + this.beamData = new dis.BeamData(); + + /** Secondary operational data, 5.2.57 */ + this.secondaryOperationalData = new dis.BeamData(); + + /** variable length list of fundamental parameters. ^^^This is wrong */ + this.fundamentalIffParameters = new Array(); + + dis.IffAtcNavAidsLayer2Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + this.layerHeader.initFromBinary(inputStream); + this.beamData.initFromBinary(inputStream); + this.secondaryOperationalData.initFromBinary(inputStream); + for(var idx = 0; idx < this.pad2; idx++) + { + var anX = new dis.FundamentalParameterDataIff(); + anX.initFromBinary(inputStream); + this.fundamentalIffParameters.push(anX); + } + + }; + + dis.IffAtcNavAidsLayer2Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + this.layerHeader.encodeToBinary(outputStream); + this.beamData.encodeToBinary(outputStream); + this.secondaryOperationalData.encodeToBinary(outputStream); + for(var idx = 0; idx < this.fundamentalIffParameters.length; idx++) + { + fundamentalIffParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer2Pdu = dis.IffAtcNavAidsLayer2Pdu; + +// End of IffAtcNavAidsLayer2Pdu class + +/** + * 5.2.42. Basic operational data ofr IFF ATC NAVAIDS + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffFundamentalData = function() +{ + /** system status */ + this.systemStatus = 0; + + /** Alternate parameter 4 */ + this.alternateParameter4 = 0; + + /** eight boolean fields */ + this.informationLayers = 0; + + /** enumeration */ + this.modifier = 0; + + /** parameter, enumeration */ + this.parameter1 = 0; + + /** parameter, enumeration */ + this.parameter2 = 0; + + /** parameter, enumeration */ + this.parameter3 = 0; + + /** parameter, enumeration */ + this.parameter4 = 0; + + /** parameter, enumeration */ + this.parameter5 = 0; + + /** parameter, enumeration */ + this.parameter6 = 0; + + dis.IffFundamentalData.prototype.initFromBinary = function(inputStream) + { + this.systemStatus = inputStream.readUByte(); + this.alternateParameter4 = inputStream.readUByte(); + this.informationLayers = inputStream.readUByte(); + this.modifier = inputStream.readUByte(); + this.parameter1 = inputStream.readUShort(); + this.parameter2 = inputStream.readUShort(); + this.parameter3 = inputStream.readUShort(); + this.parameter4 = inputStream.readUShort(); + this.parameter5 = inputStream.readUShort(); + this.parameter6 = inputStream.readUShort(); + }; + + dis.IffFundamentalData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemStatus); + outputStream.writeUByte(this.alternateParameter4); + outputStream.writeUByte(this.informationLayers); + outputStream.writeUByte(this.modifier); + outputStream.writeUShort(this.parameter1); + outputStream.writeUShort(this.parameter2); + outputStream.writeUShort(this.parameter3); + outputStream.writeUShort(this.parameter4); + outputStream.writeUShort(this.parameter5); + outputStream.writeUShort(this.parameter6); + }; +}; // end of class + + // node.js module support +exports.IffFundamentalData = dis.IffFundamentalData; + +// End of IffFundamentalData class + +/** + * 5.2.46. Intercom communcations parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomCommunicationsParameters = function() +{ + /** Type of intercom parameters record */ + this.recordType = 0; + + /** length of record-specifid field, in octets */ + this.recordLength = 0; + + /** variable length variablelist of data parameters */ + this.parameterValues = new Array(); + + dis.IntercomCommunicationsParameters.prototype.initFromBinary = function(inputStream) + { + this.recordType = inputStream.readUShort(); + this.recordLength = inputStream.readUShort(); + for(var idx = 0; idx < this.recordLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.parameterValues.push(anX); + } + + }; + + dis.IntercomCommunicationsParameters.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.recordType); + outputStream.writeUShort(this.recordLength); + for(var idx = 0; idx < this.parameterValues.length; idx++) + { + parameterValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomCommunicationsParameters = dis.IntercomCommunicationsParameters; + +// End of IntercomCommunicationsParameters class + +/** + * Section 5.3.8.5. Detailed inofrmation about the state of an intercom device and the actions it is requestion of another intercom device, or the response to a requested action. Required manual intervention to fix the intercom parameters, which can be of varialbe length. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomControlPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 32; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** control type */ + this.controlType = 0; + + /** control type */ + this.communicationsChannelType = 0; + + /** Source entity ID */ + this.sourceEntityID = new dis.EntityID(); + + /** The specific intercom device being simulated within an entity. */ + this.sourceCommunicationsDeviceID = 0; + + /** Line number to which the intercom control refers */ + this.sourceLineID = 0; + + /** priority of this message relative to transmissons from other intercom devices */ + this.transmitPriority = 0; + + /** current transmit state of the line */ + this.transmitLineState = 0; + + /** detailed type requested. */ + this.command = 0; + + /** eid of the entity that has created this intercom channel. */ + this.masterEntityID = new dis.EntityID(); + + /** specific intercom device that has created this intercom channel */ + this.masterCommunicationsDeviceID = 0; + + /** number of intercom parameters */ + this.intercomParametersLength = 0; + + /** Must be */ + this.intercomParameters = new Array(); + + dis.IntercomControlPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.controlType = inputStream.readUByte(); + this.communicationsChannelType = inputStream.readUByte(); + this.sourceEntityID.initFromBinary(inputStream); + this.sourceCommunicationsDeviceID = inputStream.readUByte(); + this.sourceLineID = inputStream.readUByte(); + this.transmitPriority = inputStream.readUByte(); + this.transmitLineState = inputStream.readUByte(); + this.command = inputStream.readUByte(); + this.masterEntityID.initFromBinary(inputStream); + this.masterCommunicationsDeviceID = inputStream.readUShort(); + this.intercomParametersLength = inputStream.readUInt(); + for(var idx = 0; idx < this.intercomParametersLength; idx++) + { + var anX = new dis.IntercomCommunicationsParameters(); + anX.initFromBinary(inputStream); + this.intercomParameters.push(anX); + } + + }; + + dis.IntercomControlPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUByte(this.controlType); + outputStream.writeUByte(this.communicationsChannelType); + this.sourceEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.sourceCommunicationsDeviceID); + outputStream.writeUByte(this.sourceLineID); + outputStream.writeUByte(this.transmitPriority); + outputStream.writeUByte(this.transmitLineState); + outputStream.writeUByte(this.command); + this.masterEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.masterCommunicationsDeviceID); + outputStream.writeUInt(this.intercomParametersLength); + for(var idx = 0; idx < this.intercomParameters.length; idx++) + { + intercomParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomControlPdu = dis.IntercomControlPdu; + +// End of IntercomControlPdu class + +/** + * Section 5.3.8.4. Actual transmission of intercome voice data. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomSignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 31; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entitythat is the source of the communication */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.communicationsDeviceID = 0; + + /** encoding scheme */ + this.encodingScheme = 0; + + /** tactical data link type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** data length, in bits */ + this.dataLength = 0; + + /** samples */ + this.samples = 0; + + /** data bytes */ + this.data = new Array(); + + dis.IntercomSignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.communicationsDeviceID = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.IntercomSignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.communicationsDeviceID); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomSignalPdu = dis.IntercomSignalPdu; + +// End of IntercomSignalPdu class + +/** + * Section 5.3.9.2 Information about a particular group of entities grouped together for the purposes of netowrk bandwidth reduction or aggregation. Needs manual cleanup. The GED size requires a database lookup. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsGroupOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 34; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.groupEntityID = new dis.EntityID(); + + /** type of entities constituting the group */ + this.groupedEntityCategory = 0; + + /** Number of individual entities constituting the group */ + this.numberOfGroupedEntities = 0; + + /** padding */ + this.pad2 = 0; + + /** latitude */ + this.latitude = 0; + + /** longitude */ + this.longitude = 0; + + /** GED records about each individual entity in the group. ^^^this is wrong--need a database lookup to find the actual size of the list elements */ + this.groupedEntityDescriptions = new Array(); + + dis.IsGroupOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.groupEntityID.initFromBinary(inputStream); + this.groupedEntityCategory = inputStream.readUByte(); + this.numberOfGroupedEntities = inputStream.readUByte(); + this.pad2 = inputStream.readUInt(); + this.latitude = inputStream.readFloat64(); + this.longitude = inputStream.readFloat64(); + for(var idx = 0; idx < this.numberOfGroupedEntities; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.groupedEntityDescriptions.push(anX); + } + + }; + + dis.IsGroupOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.groupEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.groupedEntityCategory); + outputStream.writeUByte(this.numberOfGroupedEntities); + outputStream.writeUInt(this.pad2); + outputStream.writeFloat64(this.latitude); + outputStream.writeFloat64(this.longitude); + for(var idx = 0; idx < this.groupedEntityDescriptions.length; idx++) + { + groupedEntityDescriptions[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IsGroupOfPdu = dis.IsGroupOfPdu; + +// End of IsGroupOfPdu class + +/** + * Section 5.3.9.4 The joining of two or more simulation entities is communicated by this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsPartOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 36; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating PDU */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving PDU */ + this.receivingEntityID = new dis.EntityID(); + + /** relationship of joined parts */ + this.relationship = new dis.Relationship(); + + /** location of part; centroid of part in host's coordinate system. x=range, y=bearing, z=0 */ + this.partLocation = new dis.Vector3Float(); + + /** named location */ + this.namedLocationID = new dis.NamedLocation(); + + /** entity type */ + this.partEntityType = new dis.EntityType(); + + dis.IsPartOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.relationship.initFromBinary(inputStream); + this.partLocation.initFromBinary(inputStream); + this.namedLocationID.initFromBinary(inputStream); + this.partEntityType.initFromBinary(inputStream); + }; + + dis.IsPartOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.relationship.encodeToBinary(outputStream); + this.partLocation.encodeToBinary(outputStream); + this.namedLocationID.encodeToBinary(outputStream); + this.partEntityType.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IsPartOfPdu = dis.IsPartOfPdu; + +// End of IsPartOfPdu class + +/** + * 5.2.47. Layer header. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LayerHeader = function() +{ + /** Layer number */ + this.layerNumber = 0; + + /** Layer speccific information enumeration */ + this.layerSpecificInformaiton = 0; + + /** information length */ + this.length = 0; + + dis.LayerHeader.prototype.initFromBinary = function(inputStream) + { + this.layerNumber = inputStream.readUByte(); + this.layerSpecificInformaiton = inputStream.readUByte(); + this.length = inputStream.readUShort(); + }; + + dis.LayerHeader.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.layerNumber); + outputStream.writeUByte(this.layerSpecificInformaiton); + outputStream.writeUShort(this.length); + }; +}; // end of class + + // node.js module support +exports.LayerHeader = dis.LayerHeader; + +// End of LayerHeader class + +/** + * Section 5.3.11.4: Information abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point and has size or orientation. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 44; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** number of linear segment parameters */ + this.numberOfSegments = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Linear segment parameters */ + this.linearSegmentParameters = new Array(); + + dis.LinearObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfSegments = inputStream.readUByte(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.objectType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSegments; idx++) + { + var anX = new dis.LinearSegmentParameter(); + anX.initFromBinary(inputStream); + this.linearSegmentParameters.push(anX); + } + + }; + + dis.LinearObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfSegments); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + this.objectType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.linearSegmentParameters.length; idx++) + { + linearSegmentParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.LinearObjectStatePdu = dis.LinearObjectStatePdu; + +// End of LinearObjectStatePdu class + +/** + * 5.2.48: Linear segment parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearSegmentParameter = function() +{ + /** number of segments */ + this.segmentNumber = 0; + + /** segment appearance */ + this.segmentAppearance = new dis.SixByteChunk(); + + /** location */ + this.location = new dis.Vector3Double(); + + /** orientation */ + this.orientation = new dis.Orientation(); + + /** segmentLength */ + this.segmentLength = 0; + + /** segmentWidth */ + this.segmentWidth = 0; + + /** segmentHeight */ + this.segmentHeight = 0; + + /** segment Depth */ + this.segmentDepth = 0; + + /** segment Depth */ + this.pad1 = 0; + + dis.LinearSegmentParameter.prototype.initFromBinary = function(inputStream) + { + this.segmentNumber = inputStream.readUByte(); + this.segmentAppearance.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.segmentLength = inputStream.readUShort(); + this.segmentWidth = inputStream.readUShort(); + this.segmentHeight = inputStream.readUShort(); + this.segmentDepth = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + }; + + dis.LinearSegmentParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.segmentNumber); + this.segmentAppearance.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.segmentLength); + outputStream.writeUShort(this.segmentWidth); + outputStream.writeUShort(this.segmentHeight); + outputStream.writeUShort(this.segmentDepth); + outputStream.writeUInt(this.pad1); + }; +}; // end of class + + // node.js module support +exports.LinearSegmentParameter = dis.LinearSegmentParameter; + +// End of LinearSegmentParameter class + +/** + * Section 5.3.5. Abstract superclass for logistics PDUs. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LogisticsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.LogisticsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.LogisticsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.LogisticsFamilyPdu = dis.LogisticsFamilyPdu; + +// End of LogisticsFamilyPdu class + +/** + * Section 5.2.15. Specifies the character set used inthe first byte, followed by 11 characters of text data. + * The generated Marking class should be augmented with a patch that adds getMarking() and + * setMarking() methods that convert between arrays and strings, and clamp the length + * of the string to 11 characters. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Marking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.Marking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 11; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.Marking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 11; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; + + /* + * Returns the byte array marking, in string format. + * @return string format marking characters + */ + dis.Marking.prototype.getMarking = function() + { + var marking = ""; + for(var idx = 0; idx < 11; idx++) + { + marking = marking + String.fromCharCode(this.characters[idx]); + } + + return marking; + }; + + /** + * Given a string format marking, sets the bytes of the marking object + * to the appropriate character values. Clamps the string to no more + * than 11 characters. + * + * @param {String} newMarking string format marking + * @returns {nothing} + */ + dis.Marking.prototype.setMarking = function(newMarking) + { + var stringLen = newMarking.length; + if(stringLen > 11) + stringLen = 11; + + // Copy over up to 11 characters from the string to the array + var charsCopied = 0; + while(charsCopied < stringLen) + { + this.characters[charsCopied] = newMarking.charCodeAt( charsCopied ); + charsCopied++; + } + + // Zero-fill the remainer of the character array + while(charsCopied < 11) + { + this.characters[ charsCopied ] = 0; + charsCopied++; + } + + }; +}; // end of class + + // node.js module support +exports.Marking = dis.Marking; + +// End of Marking class + +/** + * Section 5.3.10.3 Information about individual mines within a minefield. This is very, very wrong. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 39; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** ID of entity making request */ + this.requestingEntityID = new dis.EntityID(); + + /** Minefield sequence number */ + this.minefieldSequenceNumbeer = 0; + + /** request ID */ + this.requestID = 0; + + /** pdu sequence number */ + this.pduSequenceNumber = 0; + + /** number of pdus in response */ + this.numberOfPdus = 0; + + /** how many mines are in this PDU */ + this.numberOfMinesInThisPdu = 0; + + /** how many sensor type are in this PDU */ + this.numberOfSensorTypes = 0; + + /** padding */ + this.pad2 = 0; + + /** 32 boolean fields */ + this.dataFilter = 0; + + /** Mine type */ + this.mineType = new dis.EntityType(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + /** Padding to get things 32-bit aligned. ^^^this is wrong--dyanmically sized padding needed */ + this.pad3 = 0; + + /** Mine locations */ + this.mineLocation = new Array(); + + dis.MinefieldDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.minefieldSequenceNumbeer = inputStream.readUShort(); + this.requestID = inputStream.readUByte(); + this.pduSequenceNumber = inputStream.readUByte(); + this.numberOfPdus = inputStream.readUByte(); + this.numberOfMinesInThisPdu = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.mineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + this.pad3 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMinesInThisPdu; idx++) + { + var anX = new dis.Vector3Float(); + anX.initFromBinary(inputStream); + this.mineLocation.push(anX); + } + + }; + + dis.MinefieldDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequenceNumbeer); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.pduSequenceNumber); + outputStream.writeUByte(this.numberOfPdus); + outputStream.writeUByte(this.numberOfMinesInThisPdu); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.dataFilter); + this.mineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad3); + for(var idx = 0; idx < this.mineLocation.length; idx++) + { + mineLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldDataPdu = dis.MinefieldDataPdu; + +// End of MinefieldDataPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.MinefieldFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.MinefieldFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.MinefieldFamilyPdu = dis.MinefieldFamilyPdu; + +// End of MinefieldFamilyPdu class + +/** + * Section 5.3.10.2 Query a minefield for information about individual mines. Requires manual clean up to get the padding right. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 38; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** EID of entity making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** Number of perimeter points for the minefield */ + this.numberOfPerimeterPoints = 0; + + /** Padding */ + this.pad2 = 0; + + /** Number of sensor types */ + this.numberOfSensorTypes = 0; + + /** data filter, 32 boolean fields */ + this.dataFilter = 0; + + /** Entity type of mine being requested */ + this.requestedMineType = new dis.EntityType(); + + /** perimeter points of request */ + this.requestedPerimeterPoints = new Array(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + dis.MinefieldQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.requestedMineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.requestedPerimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + }; + + dis.MinefieldQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + outputStream.writeUByte(this.pad2); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUInt(this.dataFilter); + this.requestedMineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.requestedPerimeterPoints.length; idx++) + { + requestedPerimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldQueryPdu = dis.MinefieldQueryPdu; + +// End of MinefieldQueryPdu class + +/** + * Section 5.3.10.4 proivde the means to request a retransmit of a minefield data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldResponseNackPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 40; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** entity ID making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** how many pdus were missing */ + this.numberOfMissingPdus = 0; + + /** PDU sequence numbers that were missing */ + this.missingPduSequenceNumbers = new Array(); + + dis.MinefieldResponseNackPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfMissingPdus = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMissingPdus; idx++) + { + var anX = new dis.EightByteChunk(); + anX.initFromBinary(inputStream); + this.missingPduSequenceNumbers.push(anX); + } + + }; + + dis.MinefieldResponseNackPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfMissingPdus); + for(var idx = 0; idx < this.missingPduSequenceNumbers.length; idx++) + { + missingPduSequenceNumbers[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldResponseNackPdu = dis.MinefieldResponseNackPdu; + +// End of MinefieldResponseNackPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 37; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** Minefield sequence */ + this.minefieldSequence = 0; + + /** force ID */ + this.forceID = 0; + + /** Number of permieter points */ + this.numberOfPerimeterPoints = 0; + + /** type of minefield */ + this.minefieldType = new dis.EntityType(); + + /** how many mine types */ + this.numberOfMineTypes = 0; + + /** location of minefield in world coords */ + this.minefieldLocation = new dis.Vector3Double(); + + /** orientation of minefield */ + this.minefieldOrientation = new dis.Orientation(); + + /** appearance bitflags */ + this.appearance = 0; + + /** protocolMode */ + this.protocolMode = 0; + + /** perimeter points for the minefield */ + this.perimeterPoints = new Array(); + + /** Type of mines */ + this.mineType = new Array(); + + dis.MinefieldStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.minefieldSequence = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.minefieldType.initFromBinary(inputStream); + this.numberOfMineTypes = inputStream.readUShort(); + this.minefieldLocation.initFromBinary(inputStream); + this.minefieldOrientation.initFromBinary(inputStream); + this.appearance = inputStream.readUShort(); + this.protocolMode = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.perimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfMineTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.mineType.push(anX); + } + + }; + + dis.MinefieldStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequence); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + this.minefieldType.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfMineTypes); + this.minefieldLocation.encodeToBinary(outputStream); + this.minefieldOrientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.appearance); + outputStream.writeUShort(this.protocolMode); + for(var idx = 0; idx < this.perimeterPoints.length; idx++) + { + perimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.mineType.length; idx++) + { + mineType[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldStatePdu = dis.MinefieldStatePdu; + +// End of MinefieldStatePdu class + +/** + * Radio modulation + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ModulationType = function() +{ + /** spread spectrum, 16 bit boolean array */ + this.spreadSpectrum = 0; + + /** major */ + this.major = 0; + + /** detail */ + this.detail = 0; + + /** system */ + this.system = 0; + + dis.ModulationType.prototype.initFromBinary = function(inputStream) + { + this.spreadSpectrum = inputStream.readUShort(); + this.major = inputStream.readUShort(); + this.detail = inputStream.readUShort(); + this.system = inputStream.readUShort(); + }; + + dis.ModulationType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.spreadSpectrum); + outputStream.writeUShort(this.major); + outputStream.writeUShort(this.detail); + outputStream.writeUShort(this.system); + }; +}; // end of class + + // node.js module support +exports.ModulationType = dis.ModulationType; + +// End of ModulationType class + +/** + * discrete ostional relationsihip + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.NamedLocation = function() +{ + /** station name enumeration */ + this.stationName = 0; + + /** station number */ + this.stationNumber = 0; + + dis.NamedLocation.prototype.initFromBinary = function(inputStream) + { + this.stationName = inputStream.readUShort(); + this.stationNumber = inputStream.readUShort(); + }; + + dis.NamedLocation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.stationName); + outputStream.writeUShort(this.stationNumber); + }; +}; // end of class + + // node.js module support +exports.NamedLocation = dis.NamedLocation; + +// End of NamedLocation class + +/** + * Identifies type of object. This is a shorter version of EntityType that omits the specific and extra fields. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ObjectType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + dis.ObjectType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + }; + + dis.ObjectType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + }; +}; // end of class + + // node.js module support +exports.ObjectType = dis.ObjectType; + +// End of ObjectType class + +/** + * 8 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.OneByteChunk = function() +{ + /** one byte of arbitrary data */ + this.otherParameters = new Array(0); + + dis.OneByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 1; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.OneByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 1; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.OneByteChunk = dis.OneByteChunk; + +// End of OneByteChunk class + +/** + * Section 5.2.17. Three floating point values representing an orientation, psi, theta, and phi, aka the euler angles, in radians + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Orientation = function() +{ + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + dis.Orientation.prototype.initFromBinary = function(inputStream) + { + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + }; + + dis.Orientation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + }; +}; // end of class + + // node.js module support +exports.Orientation = dis.Orientation; + +// End of Orientation class + +/** + * The superclass for all PDUs. This incorporates the PduHeader record, section 5.2.29. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 0; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.Pdu = dis.Pdu; + +// End of Pdu class + +/** + * A container that holds PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduContainer = function() +{ + /** Number of PDUs in the container list */ + this.numberOfPdus = 0; + + /** List of PDUs */ + this.pdus = new Array(); + + dis.PduContainer.prototype.initFromBinary = function(inputStream) + { + this.numberOfPdus = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfPdus; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdus.push(anX); + } + + }; + + dis.PduContainer.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.numberOfPdus); + for(var idx = 0; idx < this.pdus.length; idx++) + { + pdus[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduContainer = dis.PduContainer; + +// End of PduContainer class + +/** + * Non-DIS class, used to describe streams of PDUs when logging to SQL databases + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduStream = function() +{ + /** short description of this PDU stream */ + this.shortDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Longish description of this PDU stream */ + this.longDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Name of person performing recording */ + this.personRecording = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Email of person performing recording */ + this.authorEmail = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Start time of recording, in Unix time */ + this.startTime = 0; + + /** stop time of recording, in Unix time */ + this.stopTime = 0; + + /** how many PDUs in this stream */ + this.pduCount = 0; + + /** variable length list of PDUs */ + this.pdusInStream = new Array(); + + dis.PduStream.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 256; idx++) + { + this.shortDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 512; idx++) + { + this.longDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.personRecording[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.authorEmail[ idx ] = inputStream.readByte(); + } + this.startTime = inputStream.readLong(); + this.stopTime = inputStream.readLong(); + this.pduCount = inputStream.readUInt(); + for(var idx = 0; idx < this.pduCount; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdusInStream.push(anX); + } + + }; + + dis.PduStream.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 256; idx++) + { + outputStream.writeByte(this.shortDescription[ idx ] ); + } + for(var idx = 0; idx < 512; idx++) + { + outputStream.writeByte(this.longDescription[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.personRecording[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.authorEmail[ idx ] ); + } + outputStream.writeLong(this.startTime); + outputStream.writeLong(this.stopTime); + outputStream.writeUInt(this.pduCount); + for(var idx = 0; idx < this.pdusInStream.length; idx++) + { + pdusInStream[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduStream = dis.PduStream; + +// End of PduStream class + +/** + * x,y point + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Point = function() +{ + /** x */ + this.x = 0; + + /** y */ + this.y = 0; + + dis.Point.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + }; + + dis.Point.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + }; +}; // end of class + + // node.js module support +exports.Point = dis.Point; + +// End of Point class + +/** + * Section 5.3.11.3: Inormation abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PointObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 43; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Object location */ + this.objectLocation = new dis.Vector3Double(); + + /** Object orientation */ + this.objectOrientation = new dis.Orientation(); + + /** Object apperance */ + this.objectAppearance = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** padding */ + this.pad2 = 0; + + dis.PointObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectLocation.initFromBinary(inputStream); + this.objectOrientation.initFromBinary(inputStream); + this.objectAppearance = inputStream.readFloat64(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.pad2 = inputStream.readUInt(); + }; + + dis.PointObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectLocation.encodeToBinary(outputStream); + this.objectOrientation.encodeToBinary(outputStream); + outputStream.writeFloat64(this.objectAppearance); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + outputStream.writeUInt(this.pad2); + }; +}; // end of class + + // node.js module support +exports.PointObjectStatePdu = dis.PointObjectStatePdu; + +// End of PointObjectStatePdu class + +/** + * Data about a propulsion system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PropulsionSystemData = function() +{ + /** powerSetting */ + this.powerSetting = 0; + + /** engine RPMs */ + this.engineRpm = 0; + + dis.PropulsionSystemData.prototype.initFromBinary = function(inputStream) + { + this.powerSetting = inputStream.readFloat32(); + this.engineRpm = inputStream.readFloat32(); + }; + + dis.PropulsionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.powerSetting); + outputStream.writeFloat32(this.engineRpm); + }; +}; // end of class + + // node.js module support +exports.PropulsionSystemData = dis.PropulsionSystemData; + +// End of PropulsionSystemData class + +/** + * Section 5.3.8. Abstract superclass for radio communications PDUs. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioCommunicationsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.RadioCommunicationsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.RadioCommunicationsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.RadioCommunicationsFamilyPdu = dis.RadioCommunicationsFamilyPdu; + +// End of RadioCommunicationsFamilyPdu class + +/** + * Section 5.2.25. Identifies the type of radio + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioEntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** specific info based on subcategory field */ + this.nomenclatureVersion = 0; + + this.nomenclature = 0; + + dis.RadioEntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.nomenclatureVersion = inputStream.readUByte(); + this.nomenclature = inputStream.readUShort(); + }; + + dis.RadioEntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.nomenclatureVersion); + outputStream.writeUShort(this.nomenclature); + }; +}; // end of class + + // node.js module support +exports.RadioEntityType = dis.RadioEntityType; + +// End of RadioEntityType class + +/** + * Section 5.3.8.3. Communication of a receiver state. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ReceiverPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 27; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.receiverState = 0; + + /** padding */ + this.padding1 = 0; + + /** received power */ + this.receivedPower = 0; + + /** ID of transmitter */ + this.transmitterEntityId = new dis.EntityID(); + + /** ID of transmitting radio */ + this.transmitterRadioId = 0; + + dis.ReceiverPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.receiverState = inputStream.readUShort(); + this.padding1 = inputStream.readUShort(); + this.receivedPower = inputStream.readFloat32(); + this.transmitterEntityId.initFromBinary(inputStream); + this.transmitterRadioId = inputStream.readUShort(); + }; + + dis.ReceiverPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.receiverState); + outputStream.writeUShort(this.padding1); + outputStream.writeFloat32(this.receivedPower); + this.transmitterEntityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.transmitterRadioId); + }; +}; // end of class + + // node.js module support +exports.ReceiverPdu = dis.ReceiverPdu; + +// End of ReceiverPdu class + +/** + * Section 5.3.12.13: A request for one or more records of data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 65; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** event type */ + this.eventType = 0; + + /** time */ + this.time = 0; + + /** numberOfRecords */ + this.numberOfRecords = 0; + + /** record IDs */ + this.recordIDs = new Array(); + + dis.RecordQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.eventType = inputStream.readUShort(); + this.time = inputStream.readUInt(); + this.numberOfRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecords; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.recordIDs.push(anX); + } + + }; + + dis.RecordQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.time); + outputStream.writeUInt(this.numberOfRecords); + for(var idx = 0; idx < this.recordIDs.length; idx++) + { + recordIDs[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.RecordQueryReliablePdu = dis.RecordQueryReliablePdu; + +// End of RecordQueryReliablePdu class + +/** + * Record sets, used in transfer control request PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordSet = function() +{ + /** record ID */ + this.recordID = 0; + + /** record set serial number */ + this.recordSetSerialNumber = 0; + + /** record length */ + this.recordLength = 0; + + /** record count */ + this.recordCount = 0; + + /** ^^^This is wrong--variable sized data records */ + this.recordValues = 0; + + /** ^^^This is wrong--variable sized padding */ + this.pad4 = 0; + + dis.RecordSet.prototype.initFromBinary = function(inputStream) + { + this.recordID = inputStream.readUInt(); + this.recordSetSerialNumber = inputStream.readUInt(); + this.recordLength = inputStream.readUShort(); + this.recordCount = inputStream.readUShort(); + this.recordValues = inputStream.readUShort(); + this.pad4 = inputStream.readUByte(); + }; + + dis.RecordSet.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.recordID); + outputStream.writeUInt(this.recordSetSerialNumber); + outputStream.writeUShort(this.recordLength); + outputStream.writeUShort(this.recordCount); + outputStream.writeUShort(this.recordValues); + outputStream.writeUByte(this.pad4); + }; +}; // end of class + + // node.js module support +exports.RecordSet = dis.RecordSet; + +// End of RecordSet class + +/** + * 5.2.56. Purpose for joinging two entities + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Relationship = function() +{ + /** Nature of join */ + this.nature = 0; + + /** position of join */ + this.position = 0; + + dis.Relationship.prototype.initFromBinary = function(inputStream) + { + this.nature = inputStream.readUShort(); + this.position = inputStream.readUShort(); + }; + + dis.Relationship.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.nature); + outputStream.writeUShort(this.position); + }; +}; // end of class + + // node.js module support +exports.Relationship = dis.Relationship; + +// End of Relationship class + +/** + * Section 5.3.6.2. Remove an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 12; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.RemoveEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityPdu = dis.RemoveEntityPdu; + +// End of RemoveEntityPdu class + +/** + * Section 5.3.12.2: Removal of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 52; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.RemoveEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityReliablePdu = dis.RemoveEntityReliablePdu; + +// End of RemoveEntityReliablePdu class + +/** + * Section 5.2.5.5. Repair is complete. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairCompletePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 9; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Enumeration for type of repair */ + this.repair = 0; + + /** padding, number prevents conflict with superclass ivar name */ + this.padding2 = 0; + + dis.RepairCompletePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repair = inputStream.readUShort(); + this.padding2 = inputStream.readShort(); + }; + + dis.RepairCompletePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.repair); + outputStream.writeShort(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairCompletePdu = dis.RepairCompletePdu; + +// End of RepairCompletePdu class + +/** + * Section 5.2.5.6. Sent after repair complete PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 10; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Result of repair operation */ + this.repairResult = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + dis.RepairResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repairResult = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + }; + + dis.RepairResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.repairResult); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairResponsePdu = dis.RepairResponsePdu; + +// End of RepairResponsePdu class + +/** + * Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyCancelPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 8; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + dis.ResupplyCancelPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + }; + + dis.ResupplyCancelPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.ResupplyCancelPdu = dis.ResupplyCancelPdu; + +// End of ResupplyCancelPdu class + +/** + * Section 5.3.5.2. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyOfferPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 6; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyOfferPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyOfferPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyOfferPdu = dis.ResupplyOfferPdu; + +// End of ResupplyOfferPdu class + +/** + * Section 5.3.5.3. Receipt of supplies is communiated. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyReceivedPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 7; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyReceivedPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyReceivedPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyReceivedPdu = dis.ResupplyReceivedPdu; + +// End of ResupplyReceivedPdu class + +/** + * Section 5.3.7.5. SEES PDU, supplemental emissions entity state information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SeesPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 30; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Originating entity ID */ + this.orginatingEntityID = new dis.EntityID(); + + /** IR Signature representation index */ + this.infraredSignatureRepresentationIndex = 0; + + /** acoustic Signature representation index */ + this.acousticSignatureRepresentationIndex = 0; + + /** radar cross section representation index */ + this.radarCrossSectionSignatureRepresentationIndex = 0; + + /** how many propulsion systems */ + this.numberOfPropulsionSystems = 0; + + /** how many vectoring nozzle systems */ + this.numberOfVectoringNozzleSystems = 0; + + /** variable length list of propulsion system data */ + this.propulsionSystemData = new Array(); + + /** variable length list of vectoring system data */ + this.vectoringSystemData = new Array(); + + dis.SeesPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.infraredSignatureRepresentationIndex = inputStream.readUShort(); + this.acousticSignatureRepresentationIndex = inputStream.readUShort(); + this.radarCrossSectionSignatureRepresentationIndex = inputStream.readUShort(); + this.numberOfPropulsionSystems = inputStream.readUShort(); + this.numberOfVectoringNozzleSystems = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPropulsionSystems; idx++) + { + var anX = new dis.PropulsionSystemData(); + anX.initFromBinary(inputStream); + this.propulsionSystemData.push(anX); + } + + for(var idx = 0; idx < this.numberOfVectoringNozzleSystems; idx++) + { + var anX = new dis.VectoringNozzleSystemData(); + anX.initFromBinary(inputStream); + this.vectoringSystemData.push(anX); + } + + }; + + dis.SeesPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.infraredSignatureRepresentationIndex); + outputStream.writeUShort(this.acousticSignatureRepresentationIndex); + outputStream.writeUShort(this.radarCrossSectionSignatureRepresentationIndex); + outputStream.writeUShort(this.numberOfPropulsionSystems); + outputStream.writeUShort(this.numberOfVectoringNozzleSystems); + for(var idx = 0; idx < this.propulsionSystemData.length; idx++) + { + propulsionSystemData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.vectoringSystemData.length; idx++) + { + vectoringSystemData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SeesPdu = dis.SeesPdu; + +// End of SeesPdu class + +/** + * Section 5.3.5.1. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ServiceRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 5; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is requesting service */ + this.requestingEntityID = new dis.EntityID(); + + /** Entity that is providing the service */ + this.servicingEntityID = new dis.EntityID(); + + /** type of service requested */ + this.serviceTypeRequested = 0; + + /** How many requested */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.serviceRequestPadding = 0; + + this.supplies = new Array(); + + dis.ServiceRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.requestingEntityID.initFromBinary(inputStream); + this.servicingEntityID.initFromBinary(inputStream); + this.serviceTypeRequested = inputStream.readUByte(); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.serviceRequestPadding = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ServiceRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.requestingEntityID.encodeToBinary(outputStream); + this.servicingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.serviceTypeRequested); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.serviceRequestPadding); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ServiceRequestPdu = dis.ServiceRequestPdu; + +// End of ServiceRequestPdu class + +/** + * Section 5.3.6.9. Change state information with the data contained in this. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 19; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.SetDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.SetDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataPdu = dis.SetDataPdu; + +// End of SetDataPdu class + +/** + * Section 5.3.12.9: initializing or chaning internal state information, reliable. Needs manual intervention to fix padding on variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 59; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.SetDataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.SetDataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataReliablePdu = dis.SetDataReliablePdu; + +// End of SetDataReliablePdu class + +/** + * Section 5.3.12.14: Initializing or changing internal parameter info. Needs manual intervention to fix padding in recrod set PDUs. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetRecordReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 64; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Number of record sets in list */ + this.numberOfRecordSets = 0; + + /** record sets */ + this.recordSets = new Array(); + + dis.SetRecordReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfRecordSets = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.SetRecordReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetRecordReliablePdu = dis.SetRecordReliablePdu; + +// End of SetRecordReliablePdu class + +/** + * Shaft RPMs, used in underwater acoustic clacluations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ShaftRPMs = function() +{ + /** Current shaft RPMs */ + this.currentShaftRPMs = 0; + + /** ordered shaft rpms */ + this.orderedShaftRPMs = 0; + + /** rate of change of shaft RPMs */ + this.shaftRPMRateOfChange = 0; + + dis.ShaftRPMs.prototype.initFromBinary = function(inputStream) + { + this.currentShaftRPMs = inputStream.readShort(); + this.orderedShaftRPMs = inputStream.readShort(); + this.shaftRPMRateOfChange = inputStream.readFloat32(); + }; + + dis.ShaftRPMs.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeShort(this.currentShaftRPMs); + outputStream.writeShort(this.orderedShaftRPMs); + outputStream.writeFloat32(this.shaftRPMRateOfChange); + }; +}; // end of class + + // node.js module support +exports.ShaftRPMs = dis.ShaftRPMs; + +// End of ShaftRPMs class + +/** + * Section 5.3.8.2. Detailed information about a radio transmitter. This PDU requires manually written code to complete. The encodingScheme field can be used in multiple ways, which requires hand-written code to finish. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 26; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.encodingScheme = 0; + + /** tdl type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** length of data, in bits */ + this.dataLength = 0; + + /** number of samples. If the PDU contains encoded audio, this should be zero. */ + this.samples = 0; + + /** list of eight bit values. Must be padded to fall on a 32 bit boundary. */ + this.data = new Array(); + + dis.SignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.SignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SignalPdu = dis.SignalPdu; + +// End of SignalPdu class + +/** + * Section 5.2.14.1. A Simulation Address record shall consist of the Site Identification number and the Application Identification number. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationAddress = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + dis.SimulationAddress.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + }; + + dis.SimulationAddress.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + }; +}; // end of class + + // node.js module support +exports.SimulationAddress = dis.SimulationAddress; + +// End of SimulationAddress class + +/** + * Section 5.3.6. Abstract superclass for PDUs relating to the simulation itself. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementFamilyPdu = dis.SimulationManagementFamilyPdu; + +// End of SimulationManagementFamilyPdu class + +/** + * Section 5.3.12: Abstract superclass for reliable simulation management PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementWithReliabilityFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementWithReliabilityFamilyPdu = dis.SimulationManagementWithReliabilityFamilyPdu; + +// End of SimulationManagementWithReliabilityFamilyPdu class + +/** + * 48 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SixByteChunk = function() +{ + /** six bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0); + + dis.SixByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 6; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.SixByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 6; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.SixByteChunk = dis.SixByteChunk; + +// End of SixByteChunk class + +/** + * Section 5.2.4.3. Used when the antenna pattern type in the transmitter pdu is of value 2. Specified the direction and radiation pattern from a radio transmitter's antenna. NOTE: this class must be hand-coded to clean up some implementation details. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SphericalHarmonicAntennaPattern = function() +{ + this.harmonicOrder = 0; + + dis.SphericalHarmonicAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.harmonicOrder = inputStream.readByte(); + }; + + dis.SphericalHarmonicAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeByte(this.harmonicOrder); + }; +}; // end of class + + // node.js module support +exports.SphericalHarmonicAntennaPattern = dis.SphericalHarmonicAntennaPattern; + +// End of SphericalHarmonicAntennaPattern class + +/** + * Section 5.2.6.3. Start or resume an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 13; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall start or resume */ + this.realWorldTime = new dis.ClockTime(); + + /** Simulation clock time at which the simulation shall start or resume */ + this.simulationTime = new dis.ClockTime(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.StartResumePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumePdu = dis.StartResumePdu; + +// End of StartResumePdu class + +/** + * Section 5.3.12.3: Start resume simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 53; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** time in simulation for the simulation to resume */ + this.simulationTime = new dis.ClockTime(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StartResumeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumeReliablePdu = dis.StartResumeReliablePdu; + +// End of StartResumeReliablePdu class + +/** + * Section 5.2.3.4. Stop or freeze an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 14; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall stop or freeze */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason the simulation was stopped or frozen */ + this.reason = 0; + + /** Internal behavior of the simulation and its appearance while frozento the other participants */ + this.frozenBehavior = 0; + + /** padding */ + this.padding1 = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.StopFreezePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeShort(this.padding1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezePdu = dis.StopFreezePdu; + +// End of StopFreezePdu class + +/** + * Section 5.3.12.4: Stop freeze simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 54; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason for stopping/freezing simulation */ + this.reason = 0; + + /** internal behvior of the simulation while frozen */ + this.frozenBehavior = 0; + + /** reliablity level */ + this.requiredReliablityService = 0; + + /** padding */ + this.pad1 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StopFreezeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.requiredReliablityService = inputStream.readUByte(); + this.pad1 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeUByte(this.requiredReliablityService); + outputStream.writeUByte(this.pad1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezeReliablePdu = dis.StopFreezeReliablePdu; + +// End of StopFreezeReliablePdu class + +/** + * Section 5.2.30. A supply, and the amount of that supply. Similar to an entity kind but with the addition of a quantity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SupplyQuantity = function() +{ + /** Type of supply */ + this.supplyType = new dis.EntityType(); + + /** quantity to be supplied */ + this.quantity = 0; + + dis.SupplyQuantity.prototype.initFromBinary = function(inputStream) + { + this.supplyType.initFromBinary(inputStream); + this.quantity = inputStream.readUByte(); + }; + + dis.SupplyQuantity.prototype.encodeToBinary = function(outputStream) + { + this.supplyType.encodeToBinary(outputStream); + outputStream.writeUByte(this.quantity); + }; +}; // end of class + + // node.js module support +exports.SupplyQuantity = dis.SupplyQuantity; + +// End of SupplyQuantity class + +/** + * Section 5.3.11: Abstract superclass for synthetic environment PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SyntheticEnvironmentFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.SyntheticEnvironmentFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.SyntheticEnvironmentFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.SyntheticEnvironmentFamilyPdu = dis.SyntheticEnvironmentFamilyPdu; + +// End of SyntheticEnvironmentFamilyPdu class + +/** + * 5.2.58. Used in IFF ATC PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SystemID = function() +{ + /** System Type */ + this.systemType = 0; + + /** System name, an enumeration */ + this.systemName = 0; + + /** System mode */ + this.systemMode = 0; + + /** Change Options */ + this.changeOptions = 0; + + dis.SystemID.prototype.initFromBinary = function(inputStream) + { + this.systemType = inputStream.readUShort(); + this.systemName = inputStream.readUShort(); + this.systemMode = inputStream.readUByte(); + this.changeOptions = inputStream.readUByte(); + }; + + dis.SystemID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.systemType); + outputStream.writeUShort(this.systemName); + outputStream.writeUByte(this.systemMode); + outputStream.writeUByte(this.changeOptions); + }; +}; // end of class + + // node.js module support +exports.SystemID = dis.SystemID; + +// End of SystemID class + +/** + * One track/jam target + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TrackJamTarget = function() +{ + /** track/jam target */ + this.trackJam = new dis.EntityID(); + + /** Emitter ID */ + this.emitterID = 0; + + /** beam ID */ + this.beamID = 0; + + dis.TrackJamTarget.prototype.initFromBinary = function(inputStream) + { + this.trackJam.initFromBinary(inputStream); + this.emitterID = inputStream.readUByte(); + this.beamID = inputStream.readUByte(); + }; + + dis.TrackJamTarget.prototype.encodeToBinary = function(outputStream) + { + this.trackJam.encodeToBinary(outputStream); + outputStream.writeUByte(this.emitterID); + outputStream.writeUByte(this.beamID); + }; +}; // end of class + + // node.js module support +exports.TrackJamTarget = dis.TrackJamTarget; + +// End of TrackJamTarget class + +/** + * Section 5.3.9.3 Information initiating the dyanic allocation and control of simulation entities between two simulation applications. Requires manual cleanup. The padding between record sets is variable. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransferControlRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 35; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating request */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving request */ + this.recevingEntityID = new dis.EntityID(); + + /** ID ofrequest */ + this.requestID = 0; + + /** required level of reliabliity service. */ + this.requiredReliabilityService = 0; + + /** type of transfer desired */ + this.tranferType = 0; + + /** The entity for which control is being requested to transfer */ + this.transferEntityID = new dis.EntityID(); + + /** number of record sets to transfer */ + this.numberOfRecordSets = 0; + + /** ^^^This is wrong--the RecordSet class needs more work */ + this.recordSets = new Array(); + + dis.TransferControlRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.recevingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.tranferType = inputStream.readUByte(); + this.transferEntityID.initFromBinary(inputStream); + this.numberOfRecordSets = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.TransferControlRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.recevingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUByte(this.tranferType); + this.transferEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransferControlRequestPdu = dis.TransferControlRequestPdu; + +// End of TransferControlRequestPdu class + +/** + * Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete, since the modulation parameters are of variable length. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransmitterPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 25; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** linear accelleration of entity */ + this.radioEntityType = new dis.RadioEntityType(); + + /** transmit state */ + this.transmitState = 0; + + /** input source */ + this.inputSource = 0; + + /** padding */ + this.padding1 = 0; + + /** Location of antenna */ + this.antennaLocation = new dis.Vector3Double(); + + /** relative location of antenna, in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + /** antenna pattern type */ + this.antennaPatternType = 0; + + /** atenna pattern length */ + this.antennaPatternCount = 0; + + /** frequency */ + this.frequency = 0; + + /** transmit frequency Bandwidth */ + this.transmitFrequencyBandwidth = 0; + + /** transmission power */ + this.power = 0; + + /** modulation */ + this.modulationType = new dis.ModulationType(); + + /** crypto system enumeration */ + this.cryptoSystem = 0; + + /** crypto system key identifer */ + this.cryptoKeyId = 0; + + /** how many modulation parameters we have */ + this.modulationParameterCount = 0; + + /** padding2 */ + this.padding2 = 0; + + /** padding3 */ + this.padding3 = 0; + + /** variable length list of modulation parameters */ + this.modulationParametersList = new Array(); + + /** variable length list of antenna pattern records */ + this.antennaPatternList = new Array(); + + dis.TransmitterPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.radioEntityType.initFromBinary(inputStream); + this.transmitState = inputStream.readUByte(); + this.inputSource = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + this.antennaPatternType = inputStream.readUShort(); + this.antennaPatternCount = inputStream.readUShort(); + this.frequency = inputStream.readLong(); + this.transmitFrequencyBandwidth = inputStream.readFloat32(); + this.power = inputStream.readFloat32(); + this.modulationType.initFromBinary(inputStream); + this.cryptoSystem = inputStream.readUShort(); + this.cryptoKeyId = inputStream.readUShort(); + this.modulationParameterCount = inputStream.readUByte(); + this.padding2 = inputStream.readUShort(); + this.padding3 = inputStream.readUByte(); + for(var idx = 0; idx < this.modulationParameterCount; idx++) + { + var anX = new dis.ModulationType(); + anX.initFromBinary(inputStream); + this.modulationParametersList.push(anX); + } + + for(var idx = 0; idx < this.antennaPatternCount; idx++) + { + var anX = new dis.BeamAntennaPattern(); + anX.initFromBinary(inputStream); + this.antennaPatternList.push(anX); + } + + }; + + dis.TransmitterPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + this.radioEntityType.encodeToBinary(outputStream); + outputStream.writeUByte(this.transmitState); + outputStream.writeUByte(this.inputSource); + outputStream.writeUShort(this.padding1); + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + outputStream.writeUShort(this.antennaPatternType); + outputStream.writeUShort(this.antennaPatternCount); + outputStream.writeLong(this.frequency); + outputStream.writeFloat32(this.transmitFrequencyBandwidth); + outputStream.writeFloat32(this.power); + this.modulationType.encodeToBinary(outputStream); + outputStream.writeUShort(this.cryptoSystem); + outputStream.writeUShort(this.cryptoKeyId); + outputStream.writeUByte(this.modulationParameterCount); + outputStream.writeUShort(this.padding2); + outputStream.writeUByte(this.padding3); + for(var idx = 0; idx < this.modulationParametersList.length; idx++) + { + modulationParametersList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.antennaPatternList.length; idx++) + { + antennaPatternList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransmitterPdu = dis.TransmitterPdu; + +// End of TransmitterPdu class + +/** + * 16 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TwoByteChunk = function() +{ + /** two bytes of arbitrary data */ + this.otherParameters = new Array(0, 0); + + dis.TwoByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 2; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.TwoByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 2; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.TwoByteChunk = dis.TwoByteChunk; + +// End of TwoByteChunk class + +/** + * Section 5.3.7.3. Information about underwater acoustic emmissions. This requires manual cleanup. The beam data records should ALL be a the finish, rather than attached to each emitter system. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UaPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 29; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emission */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU */ + this.stateChangeIndicator = 0; + + /** padding */ + this.pad = 0; + + /** This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. */ + this.passiveParameterIndex = 0; + + /** This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. */ + this.propulsionPlantConfiguration = 0; + + /** This field shall represent the number of shafts on a platform */ + this.numberOfShafts = 0; + + /** This field shall indicate the number of APAs described in the current UA PDU */ + this.numberOfAPAs = 0; + + /** This field shall specify the number of UA emitter systems being described in the current UA PDU */ + this.numberOfUAEmitterSystems = 0; + + /** shaft RPM values */ + this.shaftRPMs = new Array(); + + /** apaData */ + this.apaData = new Array(); + + this.emitterSystems = new Array(); + + dis.UaPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateChangeIndicator = inputStream.readByte(); + this.pad = inputStream.readByte(); + this.passiveParameterIndex = inputStream.readUShort(); + this.propulsionPlantConfiguration = inputStream.readUByte(); + this.numberOfShafts = inputStream.readUByte(); + this.numberOfAPAs = inputStream.readUByte(); + this.numberOfUAEmitterSystems = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfShafts; idx++) + { + var anX = new dis.ShaftRPMs(); + anX.initFromBinary(inputStream); + this.shaftRPMs.push(anX); + } + + for(var idx = 0; idx < this.numberOfAPAs; idx++) + { + var anX = new dis.ApaData(); + anX.initFromBinary(inputStream); + this.apaData.push(anX); + } + + for(var idx = 0; idx < this.numberOfUAEmitterSystems; idx++) + { + var anX = new dis.AcousticEmitterSystemData(); + anX.initFromBinary(inputStream); + this.emitterSystems.push(anX); + } + + }; + + dis.UaPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeByte(this.stateChangeIndicator); + outputStream.writeByte(this.pad); + outputStream.writeUShort(this.passiveParameterIndex); + outputStream.writeUByte(this.propulsionPlantConfiguration); + outputStream.writeUByte(this.numberOfShafts); + outputStream.writeUByte(this.numberOfAPAs); + outputStream.writeUByte(this.numberOfUAEmitterSystems); + for(var idx = 0; idx < this.shaftRPMs.length; idx++) + { + shaftRPMs[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.apaData.length; idx++) + { + apaData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.emitterSystems.length; idx++) + { + emitterSystems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.UaPdu = dis.UaPdu; + +// End of UaPdu class + +/** + * Wrapper for an unsigned 32 bit integer + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UnsignedIntegerWrapper = function() +{ + /** name can't be too accurate or the generated source code will have reserved word problems */ + this.wrapper = 0; + + dis.UnsignedIntegerWrapper.prototype.initFromBinary = function(inputStream) + { + this.wrapper = inputStream.readUInt(); + }; + + dis.UnsignedIntegerWrapper.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.wrapper); + }; +}; // end of class + + // node.js module support +exports.UnsignedIntegerWrapper = dis.UnsignedIntegerWrapper; + +// End of UnsignedIntegerWrapper class + +/** + * Section 5.2.32. Variable Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VariableDatum = function() +{ + /** ID of the variable datum */ + this.variableDatumID = 0; + + /** length of the variable datums, in bits. Note that this is not programmatically tied to the size of the variableData. The variable data field may be 64 bits long but only 16 bits of it could actually be used. */ + this.variableDatumLength = 0; + + /** data can be any length, but must increase in 8 byte quanta. This requires some postprocessing patches. Note that setting the data allocates a new internal array to account for the possibly increased size. The default initial size is 64 bits. */ + this.variableData = new Array(); + + dis.VariableDatum.prototype.initFromBinary = function(inputStream) + { + this.variableDatumID = inputStream.readUInt(); + this.variableDatumLength = inputStream.readUInt(); + for(var idx = 0; idx < this.variableDatumLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.variableData.push(anX); + } + + }; + + dis.VariableDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.variableDatumID); + outputStream.writeUInt(this.variableDatumLength); + for(var idx = 0; idx < this.variableData.length; idx++) + { + variableData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.VariableDatum = dis.VariableDatum; + +// End of VariableDatum class + +/** + * Section 5.3.34. Three double precision floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Double = function() +{ + /** X value */ + this.x = 0; + + /** Y value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Double.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat64(); + this.y = inputStream.readFloat64(); + this.z = inputStream.readFloat64(); + }; + + dis.Vector3Double.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat64(this.x); + outputStream.writeFloat64(this.y); + outputStream.writeFloat64(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Double = dis.Vector3Double; + +// End of Vector3Double class + +/** + * Section 5.2.33. Three floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Float = function() +{ + /** X value */ + this.x = 0; + + /** y Value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Float.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.Vector3Float.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Float = dis.Vector3Float; + +// End of Vector3Float class + +/** + * Data about a vectoring nozzle system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VectoringNozzleSystemData = function() +{ + /** horizontal deflection angle */ + this.horizontalDeflectionAngle = 0; + + /** vertical deflection angle */ + this.verticalDeflectionAngle = 0; + + dis.VectoringNozzleSystemData.prototype.initFromBinary = function(inputStream) + { + this.horizontalDeflectionAngle = inputStream.readFloat32(); + this.verticalDeflectionAngle = inputStream.readFloat32(); + }; + + dis.VectoringNozzleSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.horizontalDeflectionAngle); + outputStream.writeFloat32(this.verticalDeflectionAngle); + }; +}; // end of class + + // node.js module support +exports.VectoringNozzleSystemData = dis.VectoringNozzleSystemData; + +// End of VectoringNozzleSystemData class + +/** + * Section 5.3.4. abstract superclass for fire and detonation pdus that have shared information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.WarfareFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + dis.WarfareFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + }; + + dis.WarfareFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.WarfareFamilyPdu = dis.WarfareFamilyPdu; + +// End of WarfareFamilyPdu class + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/googleMaps.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/googleMaps.html new file mode 100644 index 0000000000000000000000000000000000000000..70f2eced01fe676b080d8a136add11845b540764 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/googleMaps.html @@ -0,0 +1,302 @@ + +<!-- +Note that if you want to use this web page from clients other than the +one running on the same host as the web browser, you MUST change the +url the websocket connects to. + +A demo that uses google map's Javascript api and web sockets. We receive +updates in IEEE 1278 DIS binary format, and place icons on the map for each +entity's location. The icons are clickable for more info. Typically the server +will be forwarding information, including from the server-local network, for such +information as may be being put out by VBS2 or the like. + +Does the conversion from DIS global (geocentric/earth-centered, earth-fixed) +to lat/lon/alt. +--> +<!DOCTYPE html> +<html> + <head> + <title>Google Maps</title> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> + + <style type="text/css"> + html {height:100%} + body { height:100%; margin:0; padding:0 } + #map-canvas{height:100% } + </style> + + + <!-- Binary DIS implementation, also coordinate system conversion utilities --> + <script type="text/javascript" src="dis.js"></script> + + <!-- Note: this is using an Google Maps API key linked to me, DMcG. For serious use, go to --> + <!-- https://code.google.com/apis/console and get your own api key. Using this key is fine for demo purposes. --> + <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAZihiWY3ho8hHfkhu9_6mcMSkxSvpjbTI&sensor=true"></script> + <!--script type="text/javascript" src="javascript/DisAppearance.js"></script--> + + </head> + <body> + <div id="map-canvas"></div> + + + <SCRIPT type="text/javascript"> + /** This works if you're running client and server on one host. To + * have it work with a remote server, replace localhost with the IP + * or name of the server. + */ + //var WEBSOCKET_URL="ws://192.168.60.204/ws"; + //var WEBSOCKET_URL="ws://172.20.82.141:8282"; + //var WEBSOCKET_URL="ws://172.20.152.19:8485"; + var WEBSOCKET_URL="ws://track.movesinstitute.org:80"; + var map; + var websocket; + /** A likely map location */ + var montereyLocation = new google.maps.LatLng(36.595, -121.877); + var orlandoLocation = new google.maps.LatLng(28.425, -81.47); + + /** Marker for the entity represented by this web browser's location */ + var ourMarker; + + /** current location of the device running this browser, as defined by geolocation api. + * This is the W3C geolocation position object, not the google maps object. + * coords.latitude, coords.longitude, coords.altitude are among the properties. + */ + var browserPosition; + + /** Hash table Used to keep track of all entities in the world */ + var allEntities = {}; + + /** EntityStatePdu for the entity represented by this page. This is + * periodically sent as a heartbeat, so others can find us. */ + var espdu = new dis.EntityStatePdu(); + espdu.marking.setMarking("IITSECDemo"); + //console.log(espdu.marking); + + //console.log(JSON.stringify(espdu)); + + /** Used to convert DIS earth-centered coordinates to lat/lon/alt */ + var conversion = new dis.CoordinateConversion(); + + /** benchmarking */ + var messageCount = 0; var startTime = new Date(); + + /** icon path*/ + var iconBase = '/images'; + + // Set the initialize function to run on page load + google.maps.event.addDomListener(window, 'load', initialize); + + /** + * Initialize the map and websocket + * + * @returns {undefined} + */ + function initialize() + { + + var coordinateConversion = new dis.CoordinateConversion(); + + var position = {}; + position.lat = 50.430436041848; + position.lon = 45.4806844718347; + position.alt = 16.2087463214993; + + var xyz = coordinateConversion.getXYZfromLatLonAltDegrees(position); + console.log("xyz for postion is ", xyz); + + var geocentric = {}; + geocentric.x = 2854437.74; + geocentric.y = 2902738.86; + geocentric.z = 4893439.36; + var geodetic = coordinateConversion.convertDisToLatLongInDegrees(geocentric); + console.log("geodetic for the same position: ", geodetic); + + // periodically prune entities that we haven't heard from lately + window.setInterval(prune, 60000); + + // The region of the map that's visible, and where it's centered. + var mapOptions = + { + center: montereyLocation, + zoom:14, + mapTypeId:google.maps.MapTypeId.SATELLITE + }; + map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); + + // Compatiability checks--not all web browsers support Websockets. + // note that the host portion of the URL (localhost here) MUST + // be changed to a DNS name or IP to reach it from off-host. The + // existing localhost is just there for development purposes. + if(window.WebSocket) + websocket = new WebSocket(WEBSOCKET_URL); + else if(Window.MozWebSocket) + websocket = new MozWebSocket(WEBSOCKET_URL); + else + alert("This web browser does not support web sockets"); + + // Set the format we want to use to receive binary messages + websocket.binaryType = 'arraybuffer'; + + // Attach functions to the the web socket for various events + websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; + websocket.onclose = function(evt){console.log("websocket close", evt);}; + websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + /** Handle the messages sent from the server to us here. We receive binary + * DIS from the server over the web socket. + * @param {event} evt The receive event object. Contains the binary data to decode + */ + websocket.onmessage = function(evt) + { + + console.log("Raw message: ", evt); + // Factory object for creating new PDUs from binary data + var pduFactory = new dis.PduFactory(); + + // InputStream is modeled on a Java input stream. Pass it binary data, + // and we will read through it, while input stream maintains a current + // place marker + //console.log(evt.data); + //var inputStream = new dis.InputStream(evt.data); + + var disMessage = pduFactory.createPdu(evt.data); + + //console.log(disMessage); + // You can trap the various types of PDU here, and + // probably call a specific function to handle each + // type of message. For now we return on everything but + // espdus. + + if(disMessage.pduType != 1) + return; + + // Some instrumentation for performance. This is useful if hooked + // up to an AIS feed, for example, which generates a lot of traffic. + + messageCount++; + if(messageCount % 500 === 0) + { + var timeNow = new Date(); + var difference = timeNow.getTime() - startTime.getTime(); + console.log("Packets per second for 20K packets: ", 20000 / difference * 1000); + startTime = new Date(); + //console.log(JSON.stringify(disMessage)); + } + + // Retrieve the entity ID from the DIS message, convert it to a JSON + // string, and then use that as a sleazy key into a "hash table" consisting + // of object attributes. + + var entityID = disMessage.entityID; + var eidString = JSON.stringify(entityID); + + // Convert from DIS global coordinates to latitude/longtitude + var latLonAlt = conversion.convertDisToLatLongInDegrees(disMessage.entityLocation); + + // We have an attribute on this object named the JSON text string, with a + // value of the marker data. Look that up. + var theMarker = allEntities[eidString]; + + // If it's not found, that means it's the first time we've heard of it. Create + // a new one. + + if(theMarker === undefined) + { + theMarker = {}; + var entityMarking = disMessage.marking.getMarking(); + + var contentString = "<b>Entity ID:</b>" + JSON.stringify(disMessage.entityID) + "<br>"; + contentString = contentString + "<b>Marking:</b>" + entityMarking + "<br>"; + contentString = contentString + "<b>Entity Type:</b>" + JSON.stringify(disMessage.entityType) + "<br>"; + contentString = contentString + "<b>Location:</b>" + latLonAlt.latitude + ", " +latLonAlt.longitude + ", " + latLonAlt.altitude + "<br>" + var infowindow = new google.maps.InfoWindow({content: contentString}); + + var newEntityLocation = new google.maps.LatLng(latLonAlt.latitude, latLonAlt.longitude); + // The marker (with the default icon) is automatically added + // to the map when created + var marker = makeMarker('tank', newEntityLocation); + + // var marker = new google.maps.Marker({ + // map:map, + // draggable:true, + // animation:google.maps.Animation.DROP, + // position: newEntityLocation, + // title:"Entity From Network", + // icon: 'tank.png' + // }); + + var iconIsBig = false; + // add a function to be called when the user clicks on the icon + google.maps.event.addListener(marker, 'click', function() + { + + if (iconIsBig){ + infowindow.close(map, marker); + marker.setIcon('tank.png'); + iconIsBig=false; + }else { + infowindow.open(map,marker); + marker.setIcon('tankBig.png'); + iconIsBig=true; + } + + }); + + theMarker.marker = marker; + + //console.log("new theMarker:", theMarker); + allEntities[eidString] = theMarker; + }; + + + // The marker for the entity has either just been added, or recognized as already + // existing. In either event, update it's position on the map. + // Update the marker position + theMarker.marker.setPosition(new google.maps.LatLng(latLonAlt.latitude, latLonAlt.longitude) ); + theMarker.lastEspdu = disMessage; + theMarker.lastHeardFrom = new Date(); + + + }; // end of onmessage + + } + + /** + * Removes icons from the map if we haven't heard from in some amount of time + */ + function prune() + { + var TIMEOUT = 120000; // 2 min + var now = new Date(); + + for (var anEntity in allEntities) + { + var entityInfo = allEntities[anEntity]; + if(now.getTime() - entityInfo.lastHeardFrom.getTime() > TIMEOUT) + { + var markerInfo = allEntities[anEntity]; + markerInfo.marker.setMap(null); + delete allEntities[anEntity]; + } + } + } + + function makeMarker(imageName,position){ + var marker = new google.maps.Marker({ + map:map, + draggable:true, + animation:google.maps.Animation.DROP, + position: position, + title:"Entity From Network", + icon: imageName +'.png' + }); + return marker; + } + + + + + </SCRIPT> + </body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/T-72-sideskirts.jpg b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/T-72-sideskirts.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1e751c86d36862259baf8845cfbaee96a1e1681f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/T-72-sideskirts.jpg differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/russian-tank.jpg b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/russian-tank.jpg new file mode 100644 index 0000000000000000000000000000000000000000..66c9bc900ed2c1058dd5337a6a682b6998521cee Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/images/russian-tank.jpg differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/russian-tank.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/russian-tank.png new file mode 100644 index 0000000000000000000000000000000000000000..686328301422a312f5000bfd882afa0f9d7a4316 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/russian-tank.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/dis.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/dis.js new file mode 100644 index 0000000000000000000000000000000000000000..83d0e716f4d5e1ab8ff391d6d4a73589abd2474e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/dis.js @@ -0,0 +1,13979 @@ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.CoordinateConversion = function() + { + + this.RADIANS_TO_DEGREES = 180.0/Math.PI; + this.DEGREES_TO_RADIANS = Math.PI/180.0; + + this.a = 6378137.0; //semi major axis (WGS 84) + this.b = 6356752.3142; //semi minor axis (WGS 84) + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.CoordinateConversion.prototype.convertDisToLatLongInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared; //second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + var a = 6378137.0; // shorter variable names + var b = 6356752.3142; + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a * a) / Math.sqrt(((a * a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var result = {latitude:answer[0] * this.RADIANS_TO_DEGREES, longitude:answer[1] * this.RADIANS_TO_DEGREES, altitude:answer[2]}; + return result; + + }; + + /** + * Converts lat long and geodetic height (elevation) into DIS XYZ + * This algorithm also uses the WGS84 ellipsoid, though you can change the values + * of a and b for a different ellipsoid. Adapted from Military Handbook 600008 + * @param latLonAlt {lat: lon: alt:} in degrees and meters + * @return {x: y: z:} in meters + */ + dis.CoordinateConversion.prototype.getXYZfromLatLonAltDegrees = function(latLonAlt) + { + var latitudeRadians = latLonAlt.lat * this.DEGREES_TO_RADIANS; + var longtitudeRadians = latLonAlt.lon * this.DEGREES_TO_RADIANS; + + var cosLat = Math.cos(latitudeRadians); + var sinLat = Math.sin(latitudeRadians); + + + var rSubN = (this.a * this.a) / Math.sqrt(((this.a * this.a) * (cosLat * cosLat) + ((this.b * this.b) * (sinLat*sinLat)))); + + var X = (rSubN + latLonAlt.alt) * cosLat * Math.cos(longtitudeRadians); + var Y = (rSubN + latLonAlt.alt) * cosLat * Math.sin(longtitudeRadians); + var Z = ((((this.b * this.b) / (this.a * this.a)) * rSubN) + latLonAlt.alt) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + }; + + exports.CoordinateConversion = dis.CoordinateConversion; +/** + * Obsolete--the code generation now includes methods for accessing bit + * fields such as this. Remains only for backward compatiblity, and I doubt + * anyone is using it. + * + * Some code to extract the entity apperance bit fields.<p> + * + * The entityAppearance field in the espdu is a 32 bit integer. To save + * space, several different fields are contained within it. + * Specifically: + * + * Name bit position Purpose + * ---- ------------ -------- + * Paint 0 0 = uniform color, 1=camo + * Mobility 1 0 = no mobility kill, 1 = mobility kill + * Fire Power 2 0 = no firepower kill, 1 = firepower kill + * Damage 3-4 0=no damange, 1=slight, 2=moderate, 3=destroyed + * Smoke 5-6 0=not smoking, 1=smoke plume, 2=emitting engine smoke, 3=engine smoke + smoke plume + * Trailing effects 7-8 dust cloud, 0=none, 1=small, 2=medium, 3=large + * hatch 9-11 0=NA, 1=hatch closed, 2=popped, 3=popped + person visible, 4=open, 5=open and visible + * head lights 12 0=off, 1=on + * tail light 13 0=off, 1=on + * brake lights 14 0=off, 1=on + * flaming 15 0=none, 1=flames present + * launcher 16 0=not raised, 1=raised + * camo type 17-18 0=desert, 1=winter, 2=forest + * concealed 19 0=not concealed, 1=prepared concealed position (netting, etc) + * frozen status 20 0=not frozen, 1=frozen (in simulation terms) + * power plant 22 0=power plant off 1=on + * state 23 0=active, 1=deactivated + * tent 24 0=not extended 1=extended + * ramp 25 0=not extended, 1=extended + * blackout lights 26 0=off, 1=on + * blackout brake 27 0=off, 1=on + * spot lights 28 0=off, 1=on + * interior lights 29 0=off, 1=on + * unused 30-31 + * + * Typical use: + * + * var entityAppearance = new DisAppearance(espdu.entityAppearance); + * var damage = entityAppearance.getBitfield(3, 4); + * + * This returns the "damage" bitfield in bits 3-4. + * + * var mobility = entityAppearance.getBitfield(1, 1); + * + * Returns the mobility field, 0 = no mobo kill, 1 = mobility kill + * + * @author DMcG + **/ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor. Takes the integer value extracted from the DIS Entity State Field appearance + * + * @param {type} integerValue the entity appearance from the espdu + * @returns {undefined} + */ +dis.DisAppearance = function(integerValue) +{ + this.entityAppearance = integerValue; +} + +/** + * Test code for creating the correct bitmask + * @returns {undefined} + */ +dis.DisAppearance.prototype.getTestMask = function() +{ + mask = 0; + for(var idx = 0; idx < 7; idx++) + { + mask = mask + this.bit_set(mask, idx); + } + + return mask; +}; + +/** + * + * @param {integer} startPosition + * @param {integer} finishPosition + * @returns {integer} + */ +dis.DisAppearance.prototype.getBitField = function(startPosition, finishPosition) +{ + // do some sanity checks + if(startPosition < 0 || startPosition > 31 || finishPosition < 0 || finishPosition > 31 || startPosition > finishPosition) + { + console.log("invalid start or finish for bitfield values: ", startPosition, " ", finishPosition); + return 0; + } + + // Develop the mask. Addition is equivalent to setting multiple bits. + var mask = 0; + for(var idx = startPosition; idx <= finishPosition; idx++) + { + mask = mask + this.bit_set(0, idx); + } + + // do the bitmask + var maskedValue = this.entityAppearance & mask; + // Shift bits to get the normalized value + var fieldValue = maskedValue >>> startPosition; + + return fieldValue; +}; + +/** Set the "bit" position in a number to 1 + * + * @param {integer} num the number whose bit we are setting. Typically zero. + * @param {integer} bit which bit to set + * @return {integer} the number passed in, with the "bit"th bit flipped on. + **/ +dis.DisAppearance.prototype.bit_set = function(num, bit) +{ + return num | 1<<bit; +} + +exports.DisAppearance = dis.DisAppearance; + +//var BigInteger = require('BigInteger'); + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.InputStream = function(binaryData) +{ + this.dataView = new DataView(binaryData, 0); // data, byte offset + this.currentPosition = 0; // ptr to "current" position in array + + dis.InputStream.prototype.readUByte = function() + { + var data = this.dataView.getUint8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readByte = function() + { + var data = this.dataView.getInt8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readUShort = function() + { + var data = this.dataView.getUint16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readShort = function() + { + var data = this.dataView.getInt16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readUInt = function() + { + var data = this.dataView.getUint32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readInt = function() + { + var data = this.dataView.getInt32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + /** Read a long integer. Assumes big endian format. Uses the BigInteger package. */ + dis.InputStream.prototype.readLongInt = function() + { + var data1 = this.dataView.getInt32(this.currentPosition); + var data2 = this.dataView.getInt32(this.currentPosition + 4); + + this.currentPosition = this.currentPosition + 8; + + }; + + dis.InputStream.prototype.readFloat32 = function() + { + var data = this.dataView.getFloat32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readFloat64 = function() + { + var data = this.dataView.getFloat64(this.currentPosition); + this.currentPosition = this.currentPosition + 8; + return data; + }; + + dis.InputStream.prototype.readLong = function() + { + console.log("Problem in dis.InputStream. Javascript cannot natively handle 64 bit ints"); + console.log("Returning 0 from read, which is almost certainly wrong"); + this.currentPosition = this.currentPosition + 8; + return 0; + }; +}; + +exports.InputStream = dis.InputStream; +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * @param binaryDataBuffer ArrayBuffer +*/ +dis.OutputStream = function(binaryDataBuffer) +{ + this.binaryData = binaryDataBuffer; + this.dataView = new DataView(this.binaryData); // data, byte offset + this.currentPosition = 0; // ptr to current position in array + + /** + * Returns a byte array trimmed to the maximum number of bytes written + * to the stream. Eg, if we initialize with a 500 byte bufer, and we + * only write 10 bytes to the output stream, this will return the first + * ten bytes of the array. + * + * @returns {ArrayBuffer} Only the data written + */ + dis.OutputStream.prototype.toByteArray = function() + { + var trimmedData = this.binaryData.slice(0, this.currentPosition); + return trimmedData; + }; + + + dis.OutputStream.prototype.writeUByte = function(userData) + { + this.dataView.setUint8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeByte = function(userData) + { + this.dataView.setInt8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeUShort = function(userData) + { + this.dataView.setUint16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeShort = function(userData) + { + this.dataView.setInt16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeUInt = function(userData) + { + this.dataView.setUint32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeInt = function(userData) + { + this.dataView.setInt32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat32 = function(userData) + { + this.dataView.setFloat32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat64 = function(userData) + { + this.dataView.setFloat64(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 8; + }; + + dis.OutputStream.prototype.writeLong = function(userData) + { + console.log("Problem in dis.outputStream. Javascript cannot natively handle 64 bit ints"); + console.log("writing 0, which is almost certainly wrong"); + this.dataView.setInt32(this.currentPosition, 0); + this.dataView.setInt32(this.currentPosition + 4, 0); + this.currentPosition = this.currentPosition + 8; + }; +}; + +exports.OutputStream = dis.OutputStream; + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + + /** + * The PDU factory is responsible for decoding binary data and turning + * it into the appropriate type of PDU. + * + * The websocket will typically send the web page a IEEE 1278.1 binary + * array of data. It could be any one of dozens of PDUs. The start of + * all PDUs is the same--they have the same header. One of the fields in + * the header is the PduType, an 8 bit integer with a unqiue value for + * each type of PDU. We have to peak at that value, decide what type + * of PDU to create of the binary we have received, and then decode it. + * + * * @DMcG + */ + + dis.PduFactory = function() + { + + }; + + /** + * decode incoming binary data and + * return the correct type of PDU. + * + * @param {type} data the IEEE 1278.1 binary data + * @returns {Pdu} Returns an instance of some PDU, be it espdu, fire, detonation, etc. Exception if PduType not known. + */ + dis.PduFactory.prototype.createPdu = function(data) + { + var asUint8Array = new Uint8Array(data); + var pduType = asUint8Array[2]; + var inputStream = new dis.InputStream(data); + var newPdu = null; + + //try + //{ + switch(pduType) + { + case 1: // entity state PDU + newPdu = new dis.EntityStatePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 2: // Fire + newPdu = new dis.FirePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 3: // detonation + newPdu = new dis.DetonationPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 4: // Collision + newPdu = new dis.CollisionPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 11: // Create entity + newPdu = new dis.CreateEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 12: // Remove entity + newPdu = new dis.RemoveEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 20: // data + newPdu = new dis.DataPdu(); + newPdu.initFromBinary(inputStream); + break; + + default: + throw "PduType: " + pduType + " Unrecognized PDUType. Add PDU in dis.PduFactory."; + } + //} + // This also picks up any errors decoding what we though was a "normal" PDU + //catch(error) + //{ + // newPdu = null; + //} + + return newPdu; + }; + + dis.PduFactory.prototype.getPdusFromBundle = function(data) + { + } + + +exports.PduFactory = dis.PduFactory; +/** + * Sets up a local tangent place (ENU) coordinate system at a given location + * and altitude, and handles conversions between geodetic, ECEF, and local + * tangent plane coordinate systems. + * + * For reference see "Conversion of Geodetic coordinates to the Local + * Tangent Plane", version 2.01, + * http://www.psas.pdx.edu/CoordinateSystem/Latitude_to_LocalTangent.pdf + * + * and "Geodetic Systems", + * http://wiki.gis.com/wiki/index.php/Geodetic_system#From_geodetic_coordinates_to_local_ENU_coordinates + * + * There's also a bunch of ancient code from older versions that someone, somewhere, + * lifted from a military handbook, originally written in C, translated to Java, + * and now translated to Javascript. + * + * Terminology: + * + * ECEF: earth centered, earth fixed coordinate system, same as DIS. Cartesian, + * origin at center of the earth, z through north pole, x out the equator and + * prime meridian, y out equator and 90 deg east. This coordinate system rotates + * with the earth, ie the x axis always points out the prime meridian and equator + * even as the earth rotates. + * + * Geodetic: latitude, longitude, altitude. + * + * WGS84: Shape of the earth, an ellipsoid roughly, with a and b the semimajor and semiminor axes + * + * ENU: East, North, Up: local coordinate system with a given geodetic origin. Tangent + * plane to the earth. + * + * All Errors mine + * + * @DMcG + * + * @param {float} lat latitude in degrees of the origin of the local tangent plane coordinate system + * @param {float} lon longitude, in degrees, of origin + * @param {float} alt altitude, in meters, of the origin of the local tangent plane coordinate system + */ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor, creates an object that can do coordinate systems conversions. + * Takes a geodetic point that is the origin of a tangent plane to the surface + * of the earth. This is useful for doing local simulation work. The local + * coordinate system has postive x east, positive y north, and positive Z up, + * aka an ENU coordinate system. Methods for converting from that coordinate system + * to the DIS (ECEF) coordinate system or geotetic coordinate systems are provided. + * + * @param {type} lat latitude, in degrees, of where the local tangent plane is located + * @param {type} lon longitude, in degrees, of the origin of the local tangent plane + * @param {type} alt altitude, in meters, of the origin of the local tangent plane + * @returns {RangeCoordinates} An object that can do coordinate system conversions + */ +dis.RangeCoordinates = function(lat, lon, alt) +{ + this.RADIANS_PER_DEGREE = 2 * Math.PI / 360.0; + this.DEGREES_PER_RADIAN = 360.0 / (2* Math.PI); + + /** WGS84 semimajor axis (constant) */ + this.a = 6378137.0; + + /** WGS84 semiminor axis (constant) */ + this.b = 6356752.3142; + + /** Ellipsoidal Flatness (constant) */ + this.f = (this.a - this.b) / this.a; // Should be 3.3528107 X 10^-3 + + /** Eccentricity (constant) */ + this.e = Math.sqrt(this.f * (2 - this.f)); // Should be 8.1819191 X 10^-2 + + // The origin of the local, East-North-Up (ENU) coordinate system, in lat/lon degrees and meters. + this.ENUOrigin = {}; + this.ENUOrigin.latitude = lat; + this.ENUOrigin.longitude = lon; + this.ENUOrigin.altitude = alt; + + // Find the origin of the ENU in earth-centered, earth-fixed ECEF aka DIS coordinates + this.ENUOriginInECEF = {}; + this.ENUOriginInECEF = this.latLonAltDegreesToECEF(lat, lon, alt); +}; + + /** Determines N, the distance from a normal plane at the given + * latitude to the Z-axis running through the center of the earth. + * This is NOT the same as the distance to the center of the earth. + * + * @param {float} lambda the latitude, in radians. + * @returns {float} distance in meters from the latitude to the axis of the earth + */ + dis.RangeCoordinates.prototype.N = function(lambda) + { + //N(lambda) = a / sqrt( 1 - e^2 * sin^2(lambda) ) + var val = this.a / Math.sqrt(1- ( Math.pow(this.e, 2) * Math.pow( Math.sin(lambda), 2) ) ); + return val; + }; + + /** + * Converts a latitude, longitude, and altitude object to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {latitude:longitude:altitude:} latLonAlt The lat/lon/alt, in degrees and meters + * @returns {x, y, z} rectilienar coordinates in ECEF, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesObjectToECEF = function(latLonAlt) + { + return this.latLonAltDegreesToECEF(latLonAlt.latitude, latLonAlt.longitude, latLonAlt.altitude); + }; + + /** + * Converts a latitude, longitude, and altitude to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {float} latitude (in radians) + * @param {float} longitude (in radians) + * @param {float} altitude (in meters) + * @returns {x, y, z} rectilienar coordinates in ECEF-r, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltRadiansToECEF = function(latitude, longitude, altitude) + { + /* + // altitude corresponds to h in the paper, lambda to latitude, phi to longitude + var x = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.cos(longitude); + var y = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.sin(longitude); + var z = (altitude + (1 - Math.pow(this.e, 2) ) * this.N(latitude)) * Math.sin(longitude); + + var coordinates = {}; + coordinates.x = x; + coordinates.y = y; + coordinates.z = z; + */ + + var cosLat = Math.cos(latitude); + var sinLat = Math.sin(latitude); + + var rSubN = (this.a*this.a) / Math.sqrt(((this.a*this.a) * (cosLat*cosLat) + ((this.b*this.b) * (sinLat*sinLat)))); + + var X = (rSubN + altitude) * cosLat * Math.cos(longitude); + var Y = (rSubN + altitude) * cosLat * Math.sin(longitude); + var Z = ((((this.b*this.b) / (this.a*this.a)) * rSubN) + altitude) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + + /* + * + * @param {type} latitude in degrees + * @param {type} longitude in degrees + * @param {type} altitude in meters + * @returns {x,y,z} coordinates in ECEF, in meters aka DIS global coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesToECEF = function(latitude, longitude, altitude) + { + return this.latLonAltRadiansToECEF(latitude * this.RADIANS_PER_DEGREE, longitude * this.RADIANS_PER_DEGREE, altitude); + }; + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. (This is + * copied from other sources than those listed above. Seems to work, though.) + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.RangeCoordinates.prototype.ECEFObjectToLatLongAltInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + var a = this.a; // semi major axis (WGS 84) + var b = this.b; //semi minor axis (WGS 84) + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared;//second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a*a) / Math.sqrt(((a*a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var ld = answer[0] * this.DEGREES_PER_RADIAN; + var lnd = answer[1] * this.DEGREES_PER_RADIAN; + var result = {latitude:ld, longitude:lnd, altitude:answer[2]}; + return result; + + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {x:y:z:} ecefPosition ecef position (in meters) + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFObjectToENU = function(ecefPosition) + { + return this.ECEFtoENU(ecefPosition.x, ecefPosition.y, ecefPosition.z); + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {float} X the X coordinate of the ECEF position + * @param {float} Y the Y coordinate + * @param {float} Z the Z coordinate + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFtoENU = function(X, Y, Z) + { + // Origin of ENU tangent plane coordinate system in ECEF coordinate system + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var originLonRadians = this.ENUOrigin.longitude * this.RADIANS_PER_DEGREE; + var originLatRadians = this.ENUOrigin.latitude * this.RADIANS_PER_DEGREE; + + e = -(Math.sin(originLonRadians)) * (X-Xr) + Math.cos(originLonRadians) * (Y-Yr); + n = -(Math.sin(originLatRadians)) * Math.cos(originLonRadians) * (X-Xr) - Math.sin(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.cos(originLatRadians) * (Z-Zr); + u = Math.cos(originLatRadians) * Math.cos(originLonRadians) * (X-Xr) + Math.cos(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.sin(originLatRadians) * (Z-Zr); + + // Local coordinate system x, y, z + return {x:e, y:n, z:u}; + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane object to ECEF, aka DIS coordinates. + * + * @param enuPosition {x:y:z:} local coordinate object + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUObjectToECEF = function(enuPosition) + { + return this.ENUtoECEF(enuPosition.x, enuPosition.y, enuPosition.z); + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane point to ECEF, aka DIS coordinates. + * + * @param localX {float} local coordinate system X + * @param localY {float} local coordinate system Y + * @param localZ {float} local coordinate system Z + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUtoECEF = function(localX, localY, localZ) + { + // ENU local coordinate system origin, in ECEF + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var refLong = this.ENUOrigin.longitude; + var refLat = this.ENUOrigin.latitude; + + /** original code this was copied from + + function [X, Y, Z] = enu2xyz(refLat, refLong, refH, e, n, u) + % Convert east, north, up coordinates (labeled e, n, u) to ECEF + % coordinates. The reference point (phi, lambda, h) must be given. All distances are in metres + + [Xr,Yr,Zr] = llh2xyz(refLat,refLong, refH); % location of reference point + + X = -sin(refLong)*e - cos(refLong)*sin(refLat)*n + cos(refLong)*cos(refLat)*u + Xr; + Y = cos(refLong)*e - sin(refLong)*sin(refLat)*n + cos(refLat)*sin(refLong)*u + Yr; + Z = cos(refLat)*n + sin(refLat)*u + Zr; + */ + + X = -(Math.sin(refLong)) * localX - Math.cos(refLong) * Math.sin(refLat) * localY + Math.cos(refLong) * Math.cos(refLat) * localZ + Xr; + Y = Math.cos(refLong) * localX - Math.sin(refLong) * Math.sin(refLat) * localY + Math.cos(refLat) * Math.sin(refLong) * localZ + Yr; + Z = Math.cos(refLat) * localY + Math.sin(refLat) * localZ + Zr; + + return {x:X, y:Y, z:Z}; + }; + +exports.RangeCoordinates = dis.RangeCoordinates;if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * Utility class that converts between strings and the DIS ESPDU marking + * field. The marking field is 12 bytes long, with the first byte being + * the character set used, and the remaining 11 bytes character codes in + * that character set. This is often used for debugging or "billboard" + * displays in 3D; it's intended for humans. The string character values + * are clamped (or filled) to exactly 11 bytes, so "This is a long string" + * will be clamped to "This is a l" (in charachter codes) and "foo" will + * be filled to "foo\0\0\0\0\0\0\0\0".<p> + * + * It is recommended that only ASCII character set (character set = 1) + * be used. + * + * @returns {undefined} + */ +dis.StringConversion = function() +{ +}; + +/** + * Given a string, returns a DIS marking field. The character set is set to + * 1, for ascii. The length is clamped to 11, and zero-filled if the string + * is shorter than 11. + * + * @returns {array} disMarking field, 12 bytes long, character set = 1 (ascii) in 0, zero-filled to 11 character codes + */ +dis.StringConversion.prototype.StringToDisMarking = function(markingString) +{ + var byteMarking = []; + + // character set 1 = ascii + byteMarking.push(1); + + var markingLength = markingString.length; + + // Clamp it to 11 bytes of character data + if(markingLength > 11) + markingLength = 11; + + // If the string is shorter than 11 bytes, we zero-fill the array + var diff = 11 - markingLength; + + for(var idx = 0; idx < markingLength; idx++) + { + byteMarking.push(markingString.charCodeAt(idx)); + } + + for(var idx = markingLength; idx < 11; idx++) + { + byteMarking.push(0); + } + + return byteMarking; +}; + +/** + * Given a DIS marking field, returns a string. Assumes always ascii. + * + * @param {array} disMarking dis marking field, [0] = character set, the rest character codes + * @returns {string} string equivalent of the marking field + */ +dis.StringConversion.prototype.DisMarkingToString = function(disMarking) +{ + var marking = ""; + + for(var idx = 1; idx < disMarking.length; idx++) + { + marking = marking + String.fromCharCode(disMarking[idx]); + } + + return marking; +}; + +// This is a temporary placeholder until full require.js code +// support is present. +if (typeof exports === "undefined") + exports = {}; + +exports.RangeCoordinates = dis.RangeCoordinates; +exports.InputStream = dis.InputStream; +exports.OutputStream = dis.OutputStream; + +/** + * Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 15; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** type of message being acknowledged */ + this.acknowledgeFlag = 0; + + /** Whether or not the receiving entity was able to comply with the request */ + this.responseFlag = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.AcknowledgePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgePdu = dis.AcknowledgePdu; + +// End of AcknowledgePdu class + +/** + * Section 5.3.12.5: Ack receipt of a start-resume, stop-freeze, create-entity or remove enitty (reliable) pdus. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 55; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** ack flags */ + this.acknowledgeFlag = 0; + + /** response flags */ + this.responseFlag = 0; + + /** Request ID */ + this.requestID = 0; + + dis.AcknowledgeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgeReliablePdu = dis.AcknowledgeReliablePdu; + +// End of AcknowledgeReliablePdu class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamData = function() +{ + /** beam data length */ + this.beamDataLength = 0; + + /** beamIDNumber */ + this.beamIDNumber = 0; + + /** padding */ + this.pad2 = 0; + + /** fundamental data parameters */ + this.fundamentalDataParameters = new dis.AcousticBeamFundamentalParameter(); + + dis.AcousticBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUShort(); + this.beamIDNumber = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.fundamentalDataParameters.initFromBinary(inputStream); + }; + + dis.AcousticBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.pad2); + this.fundamentalDataParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamData = dis.AcousticBeamData; + +// End of AcousticBeamData class + +/** + * Used in UaPdu + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamFundamentalParameter = function() +{ + /** parameter index */ + this.activeEmissionParameterIndex = 0; + + /** scan pattern */ + this.scanPattern = 0; + + /** beam center azimuth */ + this.beamCenterAzimuth = 0; + + /** azimuthal beamwidth */ + this.azimuthalBeamwidth = 0; + + /** beam center */ + this.beamCenterDE = 0; + + /** DE beamwidth (vertical beamwidth) */ + this.deBeamwidth = 0; + + dis.AcousticBeamFundamentalParameter.prototype.initFromBinary = function(inputStream) + { + this.activeEmissionParameterIndex = inputStream.readUShort(); + this.scanPattern = inputStream.readUShort(); + this.beamCenterAzimuth = inputStream.readFloat32(); + this.azimuthalBeamwidth = inputStream.readFloat32(); + this.beamCenterDE = inputStream.readFloat32(); + this.deBeamwidth = inputStream.readFloat32(); + }; + + dis.AcousticBeamFundamentalParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.activeEmissionParameterIndex); + outputStream.writeUShort(this.scanPattern); + outputStream.writeFloat32(this.beamCenterAzimuth); + outputStream.writeFloat32(this.azimuthalBeamwidth); + outputStream.writeFloat32(this.beamCenterDE); + outputStream.writeFloat32(this.deBeamwidth); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamFundamentalParameter = dis.AcousticBeamFundamentalParameter; + +// End of AcousticBeamFundamentalParameter class + +/** + * Section 5.2.35. information about a specific UA emmtter + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitter = function() +{ + /** the system for a particular UA emitter, and an enumeration */ + this.acousticName = 0; + + /** The function of the acoustic system */ + this.function = 0; + + /** The UA emitter identification number relative to a specific system */ + this.acousticIdNumber = 0; + + dis.AcousticEmitter.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.acousticIdNumber = inputStream.readUByte(); + }; + + dis.AcousticEmitter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.acousticIdNumber); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitter = dis.AcousticEmitter; + +// End of AcousticEmitter class + +/** + * 5.3.35: Information about a particular UA emitter shall be represented using an Acoustic Emitter System record. This record shall consist of three fields: Acoustic Name, Function, and Acoustic ID Number + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystem = function() +{ + /** This field shall specify the system for a particular UA emitter. */ + this.acousticName = 0; + + /** This field shall describe the function of the acoustic system. */ + this.acousticFunction = 0; + + /** This field shall specify the UA emitter identification number relative to a specific system. This field shall be represented by an 8-bit unsigned integer. This field allows the differentiation of multiple systems on an entity, even if in some instances two or more of the systems may be identical UA emitter types. Numbering of systems shall begin with the value 1. */ + this.acousticID = 0; + + dis.AcousticEmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.acousticFunction = inputStream.readUByte(); + this.acousticID = inputStream.readUByte(); + }; + + dis.AcousticEmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.acousticFunction); + outputStream.writeUByte(this.acousticID); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystem = dis.AcousticEmitterSystem; + +// End of AcousticEmitterSystem class + +/** + * Used in the UA pdu; ties together an emmitter and a location. This requires manual cleanup; the beam data should not be attached to each emitter system. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystemData = function() +{ + /** Length of emitter system data */ + this.emitterSystemDataLength = 0; + + /** Number of beams */ + this.numberOfBeams = 0; + + /** padding */ + this.pad2 = 0; + + /** This field shall specify the system for a particular UA emitter. */ + this.acousticEmitterSystem = new dis.AcousticEmitterSystem(); + + /** Represents the location wrt the entity */ + this.emitterLocation = new dis.Vector3Float(); + + /** For each beam in numberOfBeams, an emitter system. This is not right--the beam records need to be at the end of the PDU, rather than attached to each system. */ + this.beamRecords = new Array(); + + dis.AcousticEmitterSystemData.prototype.initFromBinary = function(inputStream) + { + this.emitterSystemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.acousticEmitterSystem.initFromBinary(inputStream); + this.emitterLocation.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.AcousticBeamData(); + anX.initFromBinary(inputStream); + this.beamRecords.push(anX); + } + + }; + + dis.AcousticEmitterSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.emitterSystemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.pad2); + this.acousticEmitterSystem.encodeToBinary(outputStream); + this.emitterLocation.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamRecords.length; idx++) + { + beamRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystemData = dis.AcousticEmitterSystemData; + +// End of AcousticEmitterSystemData class + +/** + * Section 5.3.6.6. Request from simulation manager to an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 16; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** identifies the action being requested */ + this.actionID = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestPdu = dis.ActionRequestPdu; + +// End of ActionRequestPdu class + +/** + * Section 5.3.12.6: request from a simulation manager to a managed entity to perform a specified action. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 56; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** request ID */ + this.actionID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionRequestReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionRequestReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestReliablePdu = dis.ActionRequestReliablePdu; + +// End of ActionRequestReliablePdu class + +/** + * Section 5.3.6.7. response to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 17; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** Status of response */ + this.requestStatus = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requestStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.requestStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponsePdu = dis.ActionResponsePdu; + +// End of ActionResponsePdu class + +/** + * Section 5.3.12.7: Response from an entity to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponseReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 57; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** status of response */ + this.responseStatus = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionResponseReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.responseStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionResponseReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.responseStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponseReliablePdu = dis.ActionResponseReliablePdu; + +// End of ActionResponseReliablePdu class + +/** + * Section 5.2.36. Each agregate in a given simulation app is given an aggregate identifier number unique for all other aggregates in that app and in that exercise. The id is valid for the duration of the the exercise. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the aggregate ID */ + this.aggregateID = 0; + + dis.AggregateID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.aggregateID = inputStream.readUShort(); + }; + + dis.AggregateID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.aggregateID); + }; +}; // end of class + + // node.js module support +exports.AggregateID = dis.AggregateID; + +// End of AggregateID class + +/** + * Section 5.2.37. Specifies the character set used inthe first byte, followed by up to 31 characters of text data. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateMarking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.AggregateMarking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 31; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.AggregateMarking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 31; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.AggregateMarking = dis.AggregateMarking; + +// End of AggregateMarking class + +/** + * Section 5.3.9.1 informationa bout aggregating entities anc communicating information about the aggregated entities. requires manual intervention to fix the padding between entityID lists and silent aggregate sysem lists--this padding is dependent on how many entityIDs there are, and needs to be on a 32 bit word boundary. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 33; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.aggregateID = new dis.EntityID(); + + /** force ID */ + this.forceID = 0; + + /** state of aggregate */ + this.aggregateState = 0; + + /** entity type of the aggregated entities */ + this.aggregateType = new dis.EntityType(); + + /** formation of aggregated entities */ + this.formation = 0; + + /** marking for aggregate; first char is charset type, rest is char data */ + this.aggregateMarking = new dis.AggregateMarking(); + + /** dimensions of bounding box for the aggregated entities, origin at the center of mass */ + this.dimensions = new dis.Vector3Float(); + + /** orientation of the bounding box */ + this.orientation = new dis.Orientation(); + + /** center of mass of the aggregation */ + this.centerOfMass = new dis.Vector3Double(); + + /** velocity of aggregation */ + this.velocity = new dis.Vector3Float(); + + /** number of aggregates */ + this.numberOfDisAggregates = 0; + + /** number of entities */ + this.numberOfDisEntities = 0; + + /** number of silent aggregate types */ + this.numberOfSilentAggregateTypes = 0; + + /** number of silent entity types */ + this.numberOfSilentEntityTypes = 0; + + /** aggregates list */ + this.aggregateIDList = new Array(); + + /** entity ID list */ + this.entityIDList = new Array(); + + /** ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed */ + this.pad2 = 0; + + /** silent entity types */ + this.silentAggregateSystemList = new Array(); + + /** silent entity types */ + this.silentEntitySystemList = new Array(); + + /** number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variableDatums */ + this.variableDatumList = new Array(); + + dis.AggregateStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.aggregateID.initFromBinary(inputStream); + this.forceID = inputStream.readUByte(); + this.aggregateState = inputStream.readUByte(); + this.aggregateType.initFromBinary(inputStream); + this.formation = inputStream.readUInt(); + this.aggregateMarking.initFromBinary(inputStream); + this.dimensions.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.centerOfMass.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.numberOfDisAggregates = inputStream.readUShort(); + this.numberOfDisEntities = inputStream.readUShort(); + this.numberOfSilentAggregateTypes = inputStream.readUShort(); + this.numberOfSilentEntityTypes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfDisAggregates; idx++) + { + var anX = new dis.AggregateID(); + anX.initFromBinary(inputStream); + this.aggregateIDList.push(anX); + } + + for(var idx = 0; idx < this.numberOfDisEntities; idx++) + { + var anX = new dis.EntityID(); + anX.initFromBinary(inputStream); + this.entityIDList.push(anX); + } + + this.pad2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfSilentAggregateTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentAggregateSystemList.push(anX); + } + + for(var idx = 0; idx < this.numberOfSilentEntityTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentEntitySystemList.push(anX); + } + + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumList.push(anX); + } + + }; + + dis.AggregateStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.aggregateID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.aggregateState); + this.aggregateType.encodeToBinary(outputStream); + outputStream.writeUInt(this.formation); + this.aggregateMarking.encodeToBinary(outputStream); + this.dimensions.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + this.centerOfMass.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfDisAggregates); + outputStream.writeUShort(this.numberOfDisEntities); + outputStream.writeUShort(this.numberOfSilentAggregateTypes); + outputStream.writeUShort(this.numberOfSilentEntityTypes); + for(var idx = 0; idx < this.aggregateIDList.length; idx++) + { + aggregateIDList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.entityIDList.length; idx++) + { + entityIDList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad2); + for(var idx = 0; idx < this.silentAggregateSystemList.length; idx++) + { + silentAggregateSystemList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.silentEntitySystemList.length; idx++) + { + silentEntitySystemList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.variableDatumList.length; idx++) + { + variableDatumList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AggregateStatePdu = dis.AggregateStatePdu; + +// End of AggregateStatePdu class + +/** + * Section 5.2.38. Identifies the type of aggregate including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateType = function() +{ + /** Kind of entity */ + this.aggregateKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field, sql has a reserved word for specific */ + this.specificInfo = 0; + + this.extra = 0; + + dis.AggregateType.prototype.initFromBinary = function(inputStream) + { + this.aggregateKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specificInfo = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.AggregateType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.aggregateKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specificInfo); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.AggregateType = dis.AggregateType; + +// End of AggregateType class + +/** + * 5.2.2: angular velocity measured in radians per second out each of the entity's own coordinate axes. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AngularVelocityVector = function() +{ + /** velocity about the x axis */ + this.x = 0; + + /** velocity about the y axis */ + this.y = 0; + + /** velocity about the zaxis */ + this.z = 0; + + dis.AngularVelocityVector.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.AngularVelocityVector.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.AngularVelocityVector = dis.AngularVelocityVector; + +// End of AngularVelocityVector class + +/** + * 5.2.3: location of the radiating portion of the antenna, specified in world coordinates and entity coordinates. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AntennaLocation = function() +{ + /** Location of the radiating portion of the antenna in world coordinates */ + this.antennaLocation = new dis.Vector3Double(); + + /** Location of the radiating portion of the antenna in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + dis.AntennaLocation.prototype.initFromBinary = function(inputStream) + { + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + }; + + dis.AntennaLocation.prototype.encodeToBinary = function(outputStream) + { + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AntennaLocation = dis.AntennaLocation; + +// End of AntennaLocation class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ApaData = function() +{ + /** Index of APA parameter */ + this.parameterIndex = 0; + + /** Index of APA parameter */ + this.parameterValue = 0; + + dis.ApaData.prototype.initFromBinary = function(inputStream) + { + this.parameterIndex = inputStream.readUShort(); + this.parameterValue = inputStream.readShort(); + }; + + dis.ApaData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.parameterIndex); + outputStream.writeShort(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ApaData = dis.ApaData; + +// End of ApaData class + +/** + * Section 5.3.11.5: Information about the addition/modification of an oobject that is geometrically achored to the terrain with a set of three or more points that come to a closure. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArealObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 45; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications enumeration */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.EntityType(); + + /** Object appearance */ + this.objectAppearance = new dis.SixByteChunk(); + + /** Number of points */ + this.numberOfPoints = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** location of object */ + this.objectLocation = new Array(); + + dis.ArealObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectAppearance.initFromBinary(inputStream); + this.numberOfPoints = inputStream.readUShort(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPoints; idx++) + { + var anX = new dis.Vector3Double(); + anX.initFromBinary(inputStream); + this.objectLocation.push(anX); + } + + }; + + dis.ArealObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectAppearance.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfPoints); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + for(var idx = 0; idx < this.objectLocation.length; idx++) + { + objectLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ArealObjectStatePdu = dis.ArealObjectStatePdu; + +// End of ArealObjectStatePdu class + +/** + * Section 5.2.5. Articulation parameters for movable parts and attached parts of an entity. Specifes wether or not a change has occured, the part identifcation of the articulated part to which it is attached, and the type and value of each parameter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArticulationParameter = function() +{ + this.parameterTypeDesignator = 0; + + this.changeIndicator = 0; + + this.partAttachedTo = 0; + + this.parameterType = 0; + + this.parameterValue = 0; + + dis.ArticulationParameter.prototype.initFromBinary = function(inputStream) + { + this.parameterTypeDesignator = inputStream.readUByte(); + this.changeIndicator = inputStream.readUByte(); + this.partAttachedTo = inputStream.readUShort(); + this.parameterType = inputStream.readInt(); + this.parameterValue = inputStream.readFloat64(); + }; + + dis.ArticulationParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.parameterTypeDesignator); + outputStream.writeUByte(this.changeIndicator); + outputStream.writeUShort(this.partAttachedTo); + outputStream.writeInt(this.parameterType); + outputStream.writeFloat64(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ArticulationParameter = dis.ArticulationParameter; + +// End of ArticulationParameter class + +/** + * Section 5.2.4.2. Used when the antenna pattern type field has a value of 1. Specifies the direction, patter, and polarization of radiation from an antenna. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamAntennaPattern = function() +{ + /** The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record. */ + this.beamDirection = new dis.Orientation(); + + this.azimuthBeamwidth = 0; + + this.elevationBeamwidth = 0; + + this.referenceSystem = 0; + + this.padding1 = 0; + + this.padding2 = 0; + + /** Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ez = 0; + + /** Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ex = 0; + + /** THe phase angle between Ez and Ex in radians. */ + this.phase = 0; + + dis.BeamAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.beamDirection.initFromBinary(inputStream); + this.azimuthBeamwidth = inputStream.readFloat32(); + this.elevationBeamwidth = inputStream.readFloat32(); + this.referenceSystem = inputStream.readFloat32(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + this.ez = inputStream.readFloat32(); + this.ex = inputStream.readFloat32(); + this.phase = inputStream.readFloat32(); + }; + + dis.BeamAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + this.beamDirection.encodeToBinary(outputStream); + outputStream.writeFloat32(this.azimuthBeamwidth); + outputStream.writeFloat32(this.elevationBeamwidth); + outputStream.writeFloat32(this.referenceSystem); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + outputStream.writeFloat32(this.ez); + outputStream.writeFloat32(this.ex); + outputStream.writeFloat32(this.phase); + }; +}; // end of class + + // node.js module support +exports.BeamAntennaPattern = dis.BeamAntennaPattern; + +// End of BeamAntennaPattern class + +/** + * Section 5.2.39. Specification of the data necessary to describe the scan volume of an emitter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamData = function() +{ + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.BeamData.prototype.initFromBinary = function(inputStream) + { + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.BeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.BeamData = dis.BeamData; + +// End of BeamData class + +/** + * Section 5.2.7. Specifies the type of muntion fired, the type of warhead, the type of fuse, the number of rounds fired, and the rate at which the roudns are fired in rounds per minute. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BurstDescriptor = function() +{ + /** What munition was used in the burst */ + this.munition = new dis.EntityType(); + + /** type of warhead */ + this.warhead = 0; + + /** type of fuse used */ + this.fuse = 0; + + /** how many of the munition were fired */ + this.quantity = 0; + + /** rate at which the munition was fired */ + this.rate = 0; + + dis.BurstDescriptor.prototype.initFromBinary = function(inputStream) + { + this.munition.initFromBinary(inputStream); + this.warhead = inputStream.readUShort(); + this.fuse = inputStream.readUShort(); + this.quantity = inputStream.readUShort(); + this.rate = inputStream.readUShort(); + }; + + dis.BurstDescriptor.prototype.encodeToBinary = function(outputStream) + { + this.munition.encodeToBinary(outputStream); + outputStream.writeUShort(this.warhead); + outputStream.writeUShort(this.fuse); + outputStream.writeUShort(this.quantity); + outputStream.writeUShort(this.rate); + }; +}; // end of class + + // node.js module support +exports.BurstDescriptor = dis.BurstDescriptor; + +// End of BurstDescriptor class + +/** + * Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ClockTime = function() +{ + /** Hours in UTC */ + this.hour = 0; + + /** Time past the hour */ + this.timePastHour = 0; + + dis.ClockTime.prototype.initFromBinary = function(inputStream) + { + this.hour = inputStream.readInt(); + this.timePastHour = inputStream.readUInt(); + }; + + dis.ClockTime.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.hour); + outputStream.writeUInt(this.timePastHour); + }; +}; // end of class + + // node.js module support +exports.ClockTime = dis.ClockTime; + +// End of ClockTime class + +/** + * 5.3.3.3. Information about elastic collisions in a DIS exercise shall be communicated using a Collision-Elastic PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionElasticPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 66; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.collisionEventID = new dis.EventID(); + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.contactVelocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + /** tensor values */ + this.collisionResultXX = 0; + + /** tensor values */ + this.collisionResultXY = 0; + + /** tensor values */ + this.collisionResultXZ = 0; + + /** tensor values */ + this.collisionResultYY = 0; + + /** tensor values */ + this.collisionResultYZ = 0; + + /** tensor values */ + this.collisionResultZZ = 0; + + /** This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates. */ + this.unitSurfaceNormal = new dis.Vector3Float(); + + /** This field shall represent the degree to which energy is conserved in a collision */ + this.coefficientOfRestitution = 0; + + dis.CollisionElasticPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.collisionEventID.initFromBinary(inputStream); + this.pad = inputStream.readShort(); + this.contactVelocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + this.collisionResultXX = inputStream.readFloat32(); + this.collisionResultXY = inputStream.readFloat32(); + this.collisionResultXZ = inputStream.readFloat32(); + this.collisionResultYY = inputStream.readFloat32(); + this.collisionResultYZ = inputStream.readFloat32(); + this.collisionResultZZ = inputStream.readFloat32(); + this.unitSurfaceNormal.initFromBinary(inputStream); + this.coefficientOfRestitution = inputStream.readFloat32(); + }; + + dis.CollisionElasticPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.collisionEventID.encodeToBinary(outputStream); + outputStream.writeShort(this.pad); + this.contactVelocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + outputStream.writeFloat32(this.collisionResultXX); + outputStream.writeFloat32(this.collisionResultXY); + outputStream.writeFloat32(this.collisionResultXZ); + outputStream.writeFloat32(this.collisionResultYY); + outputStream.writeFloat32(this.collisionResultYZ); + outputStream.writeFloat32(this.collisionResultZZ); + this.unitSurfaceNormal.encodeToBinary(outputStream); + outputStream.writeFloat32(this.coefficientOfRestitution); + }; +}; // end of class + + // node.js module support +exports.CollisionElasticPdu = dis.CollisionElasticPdu; + +// End of CollisionElasticPdu class + +/** + * Section 5.3.3.2. Information about a collision. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 4; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** ID of event */ + this.collisionType = 0; + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.velocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + dis.CollisionPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.collisionType = inputStream.readUByte(); + this.pad = inputStream.readByte(); + this.velocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + }; + + dis.CollisionPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.collisionType); + outputStream.writeByte(this.pad); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.CollisionPdu = dis.CollisionPdu; + +// End of CollisionPdu class + +/** + * Section 5.3.6.12. Arbitrary messages can be entered into the data stream via use of this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 22; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.CommentPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.CommentPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentPdu = dis.CommentPdu; + +// End of CommentPdu class + +/** + * Section 5.3.12.12: Arbitrary messages. Only reliable this time. Neds manual intervention to fix padding in variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 62; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.CommentReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.CommentReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentReliablePdu = dis.CommentReliablePdu; + +// End of CommentReliablePdu class + +/** + * Section 5.3.6.1. Create a new entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 11; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.CreateEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityPdu = dis.CreateEntityPdu; + +// End of CreateEntityPdu class + +/** + * Section 5.3.12.1: creation of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 51; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.CreateEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityReliablePdu = dis.CreateEntityReliablePdu; + +// End of CreateEntityReliablePdu class + +/** + * Section 5.3.6.10. Information issued in response to a data query pdu or a set data pdu is communicated using a data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 20; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataPdu = dis.DataPdu; + +// End of DataPdu class + +/** + * Section 5.3.6.8. Request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 18; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** time issues between issues of Data PDUs. Zero means send once only. */ + this.timeInterval = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryPdu = dis.DataQueryPdu; + +// End of DataQueryPdu class + +/** + * Section 5.3.12.8: request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 58; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** time interval between issuing data query PDUs */ + this.timeInterval = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryReliablePdu = dis.DataQueryReliablePdu; + +// End of DataQueryReliablePdu class + +/** + * Section 5.3.12.10: issued in response to a data query R or set dataR pdu. Needs manual intervention to fix padding on variable datums. UNFINSIHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 60; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataReliablePdu = dis.DataReliablePdu; + +// End of DataReliablePdu class + +/** + * represents values used in dead reckoning algorithms + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DeadReckoningParameter = function() +{ + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Linear acceleration of the entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + /** angular velocity of the entity */ + this.entityAngularVelocity = new dis.Vector3Float(); + + dis.DeadReckoningParameter.prototype.initFromBinary = function(inputStream) + { + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.entityLinearAcceleration.initFromBinary(inputStream); + this.entityAngularVelocity.initFromBinary(inputStream); + }; + + dis.DeadReckoningParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + this.entityLinearAcceleration.encodeToBinary(outputStream); + this.entityAngularVelocity.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DeadReckoningParameter = dis.DeadReckoningParameter; + +// End of DeadReckoningParameter class + +/** + * Section 5.3.7.2. Handles designating operations. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DesignatorPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 24; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity designating */ + this.designatingEntityID = new dis.EntityID(); + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.codeName = 0; + + /** ID of the entity being designated */ + this.designatedEntityID = new dis.EntityID(); + + /** This field shall identify the designator code being used by the designating entity */ + this.designatorCode = 0; + + /** This field shall identify the designator output power in watts */ + this.designatorPower = 0; + + /** This field shall identify the designator wavelength in units of microns */ + this.designatorWavelength = 0; + + /** designtor spot wrt the designated entity */ + this.designatorSpotWrtDesignated = new dis.Vector3Float(); + + /** designtor spot wrt the designated entity */ + this.designatorSpotLocation = new dis.Vector3Double(); + + /** Dead reckoning algorithm */ + this.deadReckoningAlgorithm = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** linear accelleration of entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + dis.DesignatorPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.designatingEntityID.initFromBinary(inputStream); + this.codeName = inputStream.readUShort(); + this.designatedEntityID.initFromBinary(inputStream); + this.designatorCode = inputStream.readUShort(); + this.designatorPower = inputStream.readFloat32(); + this.designatorWavelength = inputStream.readFloat32(); + this.designatorSpotWrtDesignated.initFromBinary(inputStream); + this.designatorSpotLocation.initFromBinary(inputStream); + this.deadReckoningAlgorithm = inputStream.readByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readByte(); + this.entityLinearAcceleration.initFromBinary(inputStream); + }; + + dis.DesignatorPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.designatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.codeName); + this.designatedEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.designatorCode); + outputStream.writeFloat32(this.designatorPower); + outputStream.writeFloat32(this.designatorWavelength); + this.designatorSpotWrtDesignated.encodeToBinary(outputStream); + this.designatorSpotLocation.encodeToBinary(outputStream); + outputStream.writeByte(this.deadReckoningAlgorithm); + outputStream.writeUShort(this.padding1); + outputStream.writeByte(this.padding2); + this.entityLinearAcceleration.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DesignatorPdu = dis.DesignatorPdu; + +// End of DesignatorPdu class + +/** + * Section 5.3.4.2. Information about stuff exploding. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DetonationPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 3; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of muntion that was fired */ + this.munitionID = new dis.EntityID(); + + /** ID firing event */ + this.eventID = new dis.EventID(); + + /** ID firing event */ + this.velocity = new dis.Vector3Float(); + + /** where the detonation is, in world coordinates */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munition used */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** location of the detonation or impact in the target entity's coordinate system. This information should be used for damage assessment. */ + this.locationInEntityCoordinates = new dis.Vector3Float(); + + /** result of the explosion */ + this.detonationResult = 0; + + /** How many articulation parameters we have */ + this.numberOfArticulationParameters = 0; + + /** padding */ + this.pad = 0; + + this.articulationParameters = new Array(); + + dis.DetonationPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.locationInEntityCoordinates.initFromBinary(inputStream); + this.detonationResult = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.pad = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.DetonationPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.locationInEntityCoordinates.encodeToBinary(outputStream); + outputStream.writeUByte(this.detonationResult); + outputStream.writeUByte(this.numberOfArticulationParameters); + outputStream.writeShort(this.pad); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DetonationPdu = dis.DetonationPdu; + +// End of DetonationPdu class + +/** + * Section 5.3.7. Electronic Emissions. Abstract superclass for distirubted emissions PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DistributedEmissionsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.DistributedEmissionsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.DistributedEmissionsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.DistributedEmissionsFamilyPdu = dis.DistributedEmissionsFamilyPdu; + +// End of DistributedEmissionsFamilyPdu class + +/** + * 64 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EightByteChunk = function() +{ + /** Eight bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0); + + dis.EightByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 8; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.EightByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 8; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.EightByteChunk = dis.EightByteChunk; + +// End of EightByteChunk class + +/** + * Description of one electronic emission beam + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionBeamData = function() +{ + /** This field shall specify the length of this beams data in 32 bit words */ + this.beamDataLength = 0; + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.beamIDNumber = 0; + + /** This field shall specify a Beam Parameter Index number that shall be used by receiving entities in conjunction with the Emitter Name field to provide a pointer to the stored database parameters required to regenerate the beam. */ + this.beamParameterIndex = 0; + + /** Fundamental parameter data such as frequency range, beam sweep, etc. */ + this.fundamentalParameterData = new dis.FundamentalParameterData(); + + /** beam function of a particular beam */ + this.beamFunction = 0; + + /** Number of track/jam targets */ + this.numberOfTrackJamTargets = 0; + + /** wheher or not the receiving simulation apps can assume all the targets in the scan pattern are being tracked/jammed */ + this.highDensityTrackJam = 0; + + /** padding */ + this.pad4 = 0; + + /** identify jamming techniques used */ + this.jammingModeSequence = 0; + + /** variable length variablelist of track/jam targets */ + this.trackJamTargets = new Array(); + + dis.ElectronicEmissionBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUByte(); + this.beamIDNumber = inputStream.readUByte(); + this.beamParameterIndex = inputStream.readUShort(); + this.fundamentalParameterData.initFromBinary(inputStream); + this.beamFunction = inputStream.readUByte(); + this.numberOfTrackJamTargets = inputStream.readUByte(); + this.highDensityTrackJam = inputStream.readUByte(); + this.pad4 = inputStream.readUByte(); + this.jammingModeSequence = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfTrackJamTargets; idx++) + { + var anX = new dis.TrackJamTarget(); + anX.initFromBinary(inputStream); + this.trackJamTargets.push(anX); + } + + }; + + dis.ElectronicEmissionBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.beamParameterIndex); + this.fundamentalParameterData.encodeToBinary(outputStream); + outputStream.writeUByte(this.beamFunction); + outputStream.writeUByte(this.numberOfTrackJamTargets); + outputStream.writeUByte(this.highDensityTrackJam); + outputStream.writeUByte(this.pad4); + outputStream.writeUInt(this.jammingModeSequence); + for(var idx = 0; idx < this.trackJamTargets.length; idx++) + { + trackJamTargets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionBeamData = dis.ElectronicEmissionBeamData; + +// End of ElectronicEmissionBeamData class + +/** + * Data about one electronic system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionSystemData = function() +{ + /** This field shall specify the length of this emitter system�s data (including beam data and its track/jam information) in 32-bit words. The length shall include the System Data Length field. */ + this.systemDataLength = 0; + + /** This field shall specify the number of beams being described in the current PDU for the system being described. */ + this.numberOfBeams = 0; + + /** padding. */ + this.emissionsPadding2 = 0; + + /** This field shall specify information about a particular emitter system */ + this.emitterSystem = new dis.EmitterSystem(); + + /** Location with respect to the entity */ + this.location = new dis.Vector3Float(); + + /** variable length variablelist of beam data records */ + this.beamDataRecords = new Array(); + + dis.ElectronicEmissionSystemData.prototype.initFromBinary = function(inputStream) + { + this.systemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.emissionsPadding2 = inputStream.readUShort(); + this.emitterSystem.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.ElectronicEmissionBeamData(); + anX.initFromBinary(inputStream); + this.beamDataRecords.push(anX); + } + + }; + + dis.ElectronicEmissionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.emissionsPadding2); + this.emitterSystem.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamDataRecords.length; idx++) + { + beamDataRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionSystemData = dis.ElectronicEmissionSystemData; + +// End of ElectronicEmissionSystemData class + +/** + * Section 5.3.7.1. Information about active electronic warfare (EW) emissions and active EW countermeasures shall be communicated using an Electromagnetic Emission PDU. COMPLETE (I think) + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionsPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 23; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity emitting */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)]. */ + this.stateUpdateIndicator = 0; + + /** This field shall specify the number of emission systems being described in the current PDU. */ + this.numberOfSystems = 0; + + /** padding */ + this.paddingForEmissionsPdu = 0; + + /** Electronic emmissions systems */ + this.systems = new Array(); + + dis.ElectronicEmissionsPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateUpdateIndicator = inputStream.readUByte(); + this.numberOfSystems = inputStream.readUByte(); + this.paddingForEmissionsPdu = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfSystems; idx++) + { + var anX = new dis.ElectronicEmissionSystemData(); + anX.initFromBinary(inputStream); + this.systems.push(anX); + } + + }; + + dis.ElectronicEmissionsPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.stateUpdateIndicator); + outputStream.writeUByte(this.numberOfSystems); + outputStream.writeUShort(this.paddingForEmissionsPdu); + for(var idx = 0; idx < this.systems.length; idx++) + { + systems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionsPdu = dis.ElectronicEmissionsPdu; + +// End of ElectronicEmissionsPdu class + +/** + * Section 5.2.11. This field shall specify information about a particular emitter system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EmitterSystem = function() +{ + /** Name of the emitter, 16 bit enumeration */ + this.emitterName = 0; + + /** function of the emitter, 8 bit enumeration */ + this.function = 0; + + /** emitter ID, 8 bit enumeration */ + this.emitterIdNumber = 0; + + dis.EmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.emitterName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.emitterIdNumber = inputStream.readUByte(); + }; + + dis.EmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.emitterName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.emitterIdNumber); + }; +}; // end of class + + // node.js module support +exports.EmitterSystem = dis.EmitterSystem; + +// End of EmitterSystem class + +/** + * Each entity in a given DIS simulation application shall be given an entity identifier number unique to all other entities in that application. This identifier number is valid for the duration of the exercise; however, entity identifier numbers may be reused when all possible numbers have been exhausted. No entity shall have an entity identifier number of NO_ENTITY, ALL_ENTITIES, or RQST_ASSIGN_ID. The entity iden- tifier number need not be registered or retained for future exercises. The entity identifier number shall be specified by a 16-bit unsigned integer. An entity identifier number equal to zero with valid site and application identification shall address a simulation application. An entity identifier number equal to ALL_ENTITIES shall mean all entities within the specified site and application. An entity identifier number equal to RQST_ASSIGN_ID allows the receiver of the create entity to define the entity identifier number of the new entity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + dis.EntityID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + }; + + dis.EntityID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + }; +}; // end of class + + // node.js module support +exports.EntityID = dis.EntityID; + +// End of EntityID class + +/** + * Section 5.3.3. Common superclass for EntityState, Collision, collision-elastic, and entity state update PDUs. This should be abstract. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityInformationFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityInformationFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityInformationFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityInformationFamilyPdu = dis.EntityInformationFamilyPdu; + +// End of EntityInformationFamilyPdu class + +/** + * Section 5.3.9. Common superclass for EntityManagment PDUs, including aggregate state, isGroupOf, TransferControLRequest, and isPartOf + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityManagementFamilyPdu = dis.EntityManagementFamilyPdu; + +// End of EntityManagementFamilyPdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Unique ID for an entity that is tied to this state information */ + this.entityID = new dis.EntityID(); + + /** What force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the type of entity in the world */ + this.entityType = new dis.EntityType(); + + this.alternativeEntityType = new dis.EntityType(); + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** parameters used for dead reckoning */ + this.deadReckoningParameters = new dis.DeadReckoningParameter(); + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new dis.Marking(); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.EntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityType.initFromBinary(inputStream); + this.alternativeEntityType.initFromBinary(inputStream); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningParameters.initFromBinary(inputStream); + this.marking.initFromBinary(inputStream); + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + this.entityType.encodeToBinary(outputStream); + this.alternativeEntityType.encodeToBinary(outputStream); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + this.deadReckoningParameters.encodeToBinary(outputStream); + this.marking.encodeToBinary(outputStream); + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStatePdu = dis.EntityStatePdu; + +// End of EntityStatePdu class + +/** + * 5.3.3.4. Nonstatic information about a particular entity may be communicated by issuing an Entity State Update PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStateUpdatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 67; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** This field shall identify the entity issuing the PDU */ + this.entityID = new dis.EntityID(); + + /** Padding */ + this.padding1 = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + this.articulationParameters = new Array(); + + dis.EntityStateUpdatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.padding1 = inputStream.readByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStateUpdatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeByte(this.padding1); + outputStream.writeUByte(this.numberOfArticulationParameters); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStateUpdatePdu = dis.EntityStateUpdatePdu; + +// End of EntityStateUpdatePdu class + +/** + * Section 5.2.16. Identifies the type of entity, including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Renamed from specific because that is a reserved word in SQL */ + this.spec = 0; + + this.extra = 0; + + dis.EntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.spec = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.EntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.spec); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.EntityType = dis.EntityType; + +// End of EntityType class + +/** + * Section 5.2.40. Information about a geometry, a state associated with a geometry, a bounding volume, or an associated entity ID. NOTE: this class requires hand coding. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Environment = function() +{ + /** Record type */ + this.environmentType = 0; + + /** length, in bits */ + this.length = 0; + + /** Identify the sequentially numbered record index */ + this.recordIndex = 0; + + /** padding */ + this.padding1 = 0; + + /** Geometry or state record */ + this.geometry = 0; + + /** padding to bring the total size up to a 64 bit boundry */ + this.padding2 = 0; + + dis.Environment.prototype.initFromBinary = function(inputStream) + { + this.environmentType = inputStream.readUInt(); + this.length = inputStream.readUByte(); + this.recordIndex = inputStream.readUByte(); + this.padding1 = inputStream.readUByte(); + this.geometry = inputStream.readUByte(); + this.padding2 = inputStream.readUByte(); + }; + + dis.Environment.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.environmentType); + outputStream.writeUByte(this.length); + outputStream.writeUByte(this.recordIndex); + outputStream.writeUByte(this.padding1); + outputStream.writeUByte(this.geometry); + outputStream.writeUByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.Environment = dis.Environment; + +// End of Environment class + +/** + * Section 5.3.11.1: Information about environmental effects and processes. This requires manual cleanup. the environmental record is variable, as is the padding. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EnvironmentalProcessPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 41; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Environmental process ID */ + this.environementalProcessID = new dis.EntityID(); + + /** Environment type */ + this.environmentType = new dis.EntityType(); + + /** model type */ + this.modelType = 0; + + /** Environment status */ + this.environmentStatus = 0; + + /** number of environment records */ + this.numberOfEnvironmentRecords = 0; + + /** PDU sequence number for the environmentla process if pdu sequencing required */ + this.sequenceNumber = 0; + + /** environemt records */ + this.environmentRecords = new Array(); + + dis.EnvironmentalProcessPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environementalProcessID.initFromBinary(inputStream); + this.environmentType.initFromBinary(inputStream); + this.modelType = inputStream.readUByte(); + this.environmentStatus = inputStream.readUByte(); + this.numberOfEnvironmentRecords = inputStream.readUByte(); + this.sequenceNumber = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfEnvironmentRecords; idx++) + { + var anX = new dis.Environment(); + anX.initFromBinary(inputStream); + this.environmentRecords.push(anX); + } + + }; + + dis.EnvironmentalProcessPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environementalProcessID.encodeToBinary(outputStream); + this.environmentType.encodeToBinary(outputStream); + outputStream.writeUByte(this.modelType); + outputStream.writeUByte(this.environmentStatus); + outputStream.writeUByte(this.numberOfEnvironmentRecords); + outputStream.writeUShort(this.sequenceNumber); + for(var idx = 0; idx < this.environmentRecords.length; idx++) + { + environmentRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EnvironmentalProcessPdu = dis.EnvironmentalProcessPdu; + +// End of EnvironmentalProcessPdu class + +/** + * Section 5.2.18. Identifies a unique event in a simulation via the combination of three values + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the number of the event */ + this.eventNumber = 0; + + dis.EventID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.eventNumber = inputStream.readUShort(); + }; + + dis.EventID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.eventNumber); + }; +}; // end of class + + // node.js module support +exports.EventID = dis.EventID; + +// End of EventID class + +/** + * Section 5.3.6.11. Reports occurance of a significant event to the simulation manager. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 21; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Type of event */ + this.eventType = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.EventReportPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.EventReportPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.eventType); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportPdu = dis.EventReportPdu; + +// End of EventReportPdu class + +/** + * Section 5.3.12.11: reports the occurance of a significatnt event to the simulation manager. Needs manual intervention to fix padding in variable datums. UNFINISHED. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 61; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Event type */ + this.eventType = 0; + + /** padding */ + this.pad1 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.EventReportReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.EventReportReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.pad1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportReliablePdu = dis.EventReportReliablePdu; + +// End of EventReportReliablePdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. This is identical in function to entity state pdu, but generates less garbage to collect in the Java world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FastEntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + /** what force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Name changed from specific because that is a reserved word in SQL. */ + this.specif = 0; + + this.extra = 0; + + /** Kind of entity */ + this.altEntityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.altDomain = 0; + + /** country to which the design of the entity is attributed */ + this.altCountry = 0; + + /** category of entity */ + this.altCategory = 0; + + /** subcategory of entity */ + this.altSubcategory = 0; + + /** specific info based on subcategory field */ + this.altSpecific = 0; + + this.altExtra = 0; + + /** X velo */ + this.xVelocity = 0; + + /** y Value */ + this.yVelocity = 0; + + /** Z value */ + this.zVelocity = 0; + + /** X value */ + this.xLocation = 0; + + /** y Value */ + this.yLocation = 0; + + /** Z value */ + this.zLocation = 0; + + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** X value */ + this.xAcceleration = 0; + + /** y Value */ + this.yAcceleration = 0; + + /** Z value */ + this.zAcceleration = 0; + + /** X value */ + this.xAngularVelocity = 0; + + /** y Value */ + this.yAngularVelocity = 0; + + /** Z value */ + this.zAngularVelocity = 0; + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.FastEntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specif = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + this.altEntityKind = inputStream.readUByte(); + this.altDomain = inputStream.readUByte(); + this.altCountry = inputStream.readUShort(); + this.altCategory = inputStream.readUByte(); + this.altSubcategory = inputStream.readUByte(); + this.altSpecific = inputStream.readUByte(); + this.altExtra = inputStream.readUByte(); + this.xVelocity = inputStream.readFloat32(); + this.yVelocity = inputStream.readFloat32(); + this.zVelocity = inputStream.readFloat32(); + this.xLocation = inputStream.readFloat64(); + this.yLocation = inputStream.readFloat64(); + this.zLocation = inputStream.readFloat64(); + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.xAcceleration = inputStream.readFloat32(); + this.yAcceleration = inputStream.readFloat32(); + this.zAcceleration = inputStream.readFloat32(); + this.xAngularVelocity = inputStream.readFloat32(); + this.yAngularVelocity = inputStream.readFloat32(); + this.zAngularVelocity = inputStream.readFloat32(); + for(var idx = 0; idx < 12; idx++) + { + this.marking[ idx ] = inputStream.readByte(); + } + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.FastEntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specif); + outputStream.writeUByte(this.extra); + outputStream.writeUByte(this.altEntityKind); + outputStream.writeUByte(this.altDomain); + outputStream.writeUShort(this.altCountry); + outputStream.writeUByte(this.altCategory); + outputStream.writeUByte(this.altSubcategory); + outputStream.writeUByte(this.altSpecific); + outputStream.writeUByte(this.altExtra); + outputStream.writeFloat32(this.xVelocity); + outputStream.writeFloat32(this.yVelocity); + outputStream.writeFloat32(this.zVelocity); + outputStream.writeFloat64(this.xLocation); + outputStream.writeFloat64(this.yLocation); + outputStream.writeFloat64(this.zLocation); + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + outputStream.writeInt(this.entityAppearance); + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + outputStream.writeFloat32(this.xAcceleration); + outputStream.writeFloat32(this.yAcceleration); + outputStream.writeFloat32(this.zAcceleration); + outputStream.writeFloat32(this.xAngularVelocity); + outputStream.writeFloat32(this.yAngularVelocity); + outputStream.writeFloat32(this.zAngularVelocity); + for(var idx = 0; idx < 12; idx++) + { + outputStream.writeByte(this.marking[ idx ] ); + } + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.FastEntityStatePdu = dis.FastEntityStatePdu; + +// End of FastEntityStatePdu class + +/** + * Sectioin 5.3.4.1. Information about someone firing something. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FirePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 2; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of the munition that is being shot */ + this.munitionID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + this.fireMissionIndex = 0; + + /** location of the firing event */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munitions used in the firing event */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** Velocity of the ammunition */ + this.velocity = new dis.Vector3Float(); + + /** range to the target. Note the word range is a SQL reserved word. */ + this.rangeToTarget = 0; + + dis.FirePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.fireMissionIndex = inputStream.readInt(); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.rangeToTarget = inputStream.readFloat32(); + }; + + dis.FirePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeInt(this.fireMissionIndex); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.rangeToTarget); + }; +}; // end of class + + // node.js module support +exports.FirePdu = dis.FirePdu; + +// End of FirePdu class + +/** + * Section 5.2.18. Fixed Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FixedDatum = function() +{ + /** ID of the fixed datum */ + this.fixedDatumID = 0; + + /** Value for the fixed datum */ + this.fixedDatumValue = 0; + + dis.FixedDatum.prototype.initFromBinary = function(inputStream) + { + this.fixedDatumID = inputStream.readUInt(); + this.fixedDatumValue = inputStream.readUInt(); + }; + + dis.FixedDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.fixedDatumID); + outputStream.writeUInt(this.fixedDatumValue); + }; +}; // end of class + + // node.js module support +exports.FixedDatum = dis.FixedDatum; + +// End of FixedDatum class + +/** + * 32 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FourByteChunk = function() +{ + /** four bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0); + + dis.FourByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 4; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.FourByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 4; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.FourByteChunk = dis.FourByteChunk; + +// End of FourByteChunk class + +/** + * Section 5.2.22. Contains electromagnetic emmision regineratin parameters that are variable throughout a scenario dependent on the actions of the participants in the simulation. Also provides basic parametric data that may be used to support low-fidelity simulations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterData = function() +{ + /** center frequency of the emission in hertz. */ + this.frequency = 0; + + /** Bandwidth of the frequencies corresponding to the fequency field. */ + this.frequencyRange = 0; + + /** Effective radiated power for the emission in DdBm. For a radar noise jammer, indicates the peak of the transmitted power. */ + this.effectiveRadiatedPower = 0; + + /** Average repetition frequency of the emission in hertz. */ + this.pulseRepetitionFrequency = 0; + + /** Average pulse width of the emission in microseconds. */ + this.pulseWidth = 0; + + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.FundamentalParameterData.prototype.initFromBinary = function(inputStream) + { + this.frequency = inputStream.readFloat32(); + this.frequencyRange = inputStream.readFloat32(); + this.effectiveRadiatedPower = inputStream.readFloat32(); + this.pulseRepetitionFrequency = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.FundamentalParameterData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.frequencyRange); + outputStream.writeFloat32(this.effectiveRadiatedPower); + outputStream.writeFloat32(this.pulseRepetitionFrequency); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterData = dis.FundamentalParameterData; + +// End of FundamentalParameterData class + +/** + * 5.2.45. Fundamental IFF atc data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterDataIff = function() +{ + /** ERP */ + this.erp = 0; + + /** frequency */ + this.frequency = 0; + + /** pgrf */ + this.pgrf = 0; + + /** Pulse width */ + this.pulseWidth = 0; + + /** Burst length */ + this.burstLength = 0; + + /** Applicable modes enumeration */ + this.applicableModes = 0; + + /** padding */ + this.pad2 = 0; + + /** padding */ + this.pad3 = 0; + + dis.FundamentalParameterDataIff.prototype.initFromBinary = function(inputStream) + { + this.erp = inputStream.readFloat32(); + this.frequency = inputStream.readFloat32(); + this.pgrf = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.burstLength = inputStream.readUInt(); + this.applicableModes = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.pad3 = inputStream.readUByte(); + }; + + dis.FundamentalParameterDataIff.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.erp); + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.pgrf); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeUInt(this.burstLength); + outputStream.writeUByte(this.applicableModes); + outputStream.writeUShort(this.pad2); + outputStream.writeUByte(this.pad3); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterDataIff = dis.FundamentalParameterDataIff; + +// End of FundamentalParameterDataIff class + +/** + * 5.2.44: Grid data record, a common abstract superclass for several subtypes + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecord = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + dis.GridAxisRecord.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + }; + + dis.GridAxisRecord.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + }; +}; // end of class + + // node.js module support +exports.GridAxisRecord = dis.GridAxisRecord; + +// End of GridAxisRecord class + +/** + * 5.2.44: Grid data record, representation 0 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation0 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of bytes of environmental state data */ + this.numberOfBytes = 0; + + /** variable length variablelist of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation0.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfBytes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfBytes; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation0.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfBytes); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation0 = dis.GridAxisRecordRepresentation0; + +// End of GridAxisRecordRepresentation0 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation1 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** constant scale factor */ + this.fieldScale = 0; + + /** constant offset used to scale grid data */ + this.fieldOffset = 0; + + /** Number of data values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation1.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.fieldScale = inputStream.readFloat32(); + this.fieldOffset = inputStream.readFloat32(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation1.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeFloat32(this.fieldScale); + outputStream.writeFloat32(this.fieldOffset); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation1 = dis.GridAxisRecordRepresentation1; + +// End of GridAxisRecordRepresentation1 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation2 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation2.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation2.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation2 = dis.GridAxisRecordRepresentation2; + +// End of GridAxisRecordRepresentation2 class + +/** + * Section 5.3.11.2: Information about globat, spatially varying enviornmental effects. This requires manual cleanup; the grid axis records are variable sized. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GriddedDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 42; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** environmental simulation application ID */ + this.environmentalSimulationApplicationID = new dis.EntityID(); + + /** unique identifier for each piece of enviornmental data */ + this.fieldNumber = 0; + + /** sequence number for the total set of PDUS used to transmit the data */ + this.pduNumber = 0; + + /** Total number of PDUS used to transmit the data */ + this.pduTotal = 0; + + /** coordinate system of the grid */ + this.coordinateSystem = 0; + + /** number of grid axes for the environmental data */ + this.numberOfGridAxes = 0; + + /** are domain grid axes identidal to those of the priveious domain update? */ + this.constantGrid = 0; + + /** type of environment */ + this.environmentType = new dis.EntityType(); + + /** orientation of the data grid */ + this.orientation = new dis.Orientation(); + + /** valid time of the enviormental data sample, 64 bit unsigned int */ + this.sampleTime = 0; + + /** total number of all data values for all pdus for an environmental sample */ + this.totalValues = 0; + + /** total number of data values at each grid point. */ + this.vectorDimension = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** Grid data ^^^This is wrong */ + this.gridDataList = new Array(); + + dis.GriddedDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environmentalSimulationApplicationID.initFromBinary(inputStream); + this.fieldNumber = inputStream.readUShort(); + this.pduNumber = inputStream.readUShort(); + this.pduTotal = inputStream.readUShort(); + this.coordinateSystem = inputStream.readUShort(); + this.numberOfGridAxes = inputStream.readUByte(); + this.constantGrid = inputStream.readUByte(); + this.environmentType.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.sampleTime = inputStream.readLong(); + this.totalValues = inputStream.readUInt(); + this.vectorDimension = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfGridAxes; idx++) + { + var anX = new dis.GridAxisRecord(); + anX.initFromBinary(inputStream); + this.gridDataList.push(anX); + } + + }; + + dis.GriddedDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environmentalSimulationApplicationID.encodeToBinary(outputStream); + outputStream.writeUShort(this.fieldNumber); + outputStream.writeUShort(this.pduNumber); + outputStream.writeUShort(this.pduTotal); + outputStream.writeUShort(this.coordinateSystem); + outputStream.writeUByte(this.numberOfGridAxes); + outputStream.writeUByte(this.constantGrid); + this.environmentType.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeLong(this.sampleTime); + outputStream.writeUInt(this.totalValues); + outputStream.writeUByte(this.vectorDimension); + outputStream.writeUShort(this.padding1); + outputStream.writeUByte(this.padding2); + for(var idx = 0; idx < this.gridDataList.length; idx++) + { + gridDataList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GriddedDataPdu = dis.GriddedDataPdu; + +// End of GriddedDataPdu class + +/** + * 5.3.7.4.1: Navigational and IFF PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer1Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + dis.IffAtcNavAidsLayer1Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + }; + + dis.IffAtcNavAidsLayer1Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer1Pdu = dis.IffAtcNavAidsLayer1Pdu; + +// End of IffAtcNavAidsLayer1Pdu class + +/** + * Section 5.3.7.4.2 When present, layer 2 should follow layer 1 and have the following fields. This requires manual cleanup. the beamData attribute semantics are used in multiple ways. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer2Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + /** layer header */ + this.layerHeader = new dis.LayerHeader(); + + /** beam data */ + this.beamData = new dis.BeamData(); + + /** Secondary operational data, 5.2.57 */ + this.secondaryOperationalData = new dis.BeamData(); + + /** variable length list of fundamental parameters. ^^^This is wrong */ + this.fundamentalIffParameters = new Array(); + + dis.IffAtcNavAidsLayer2Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + this.layerHeader.initFromBinary(inputStream); + this.beamData.initFromBinary(inputStream); + this.secondaryOperationalData.initFromBinary(inputStream); + for(var idx = 0; idx < this.pad2; idx++) + { + var anX = new dis.FundamentalParameterDataIff(); + anX.initFromBinary(inputStream); + this.fundamentalIffParameters.push(anX); + } + + }; + + dis.IffAtcNavAidsLayer2Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + this.layerHeader.encodeToBinary(outputStream); + this.beamData.encodeToBinary(outputStream); + this.secondaryOperationalData.encodeToBinary(outputStream); + for(var idx = 0; idx < this.fundamentalIffParameters.length; idx++) + { + fundamentalIffParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer2Pdu = dis.IffAtcNavAidsLayer2Pdu; + +// End of IffAtcNavAidsLayer2Pdu class + +/** + * 5.2.42. Basic operational data ofr IFF ATC NAVAIDS + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffFundamentalData = function() +{ + /** system status */ + this.systemStatus = 0; + + /** Alternate parameter 4 */ + this.alternateParameter4 = 0; + + /** eight boolean fields */ + this.informationLayers = 0; + + /** enumeration */ + this.modifier = 0; + + /** parameter, enumeration */ + this.parameter1 = 0; + + /** parameter, enumeration */ + this.parameter2 = 0; + + /** parameter, enumeration */ + this.parameter3 = 0; + + /** parameter, enumeration */ + this.parameter4 = 0; + + /** parameter, enumeration */ + this.parameter5 = 0; + + /** parameter, enumeration */ + this.parameter6 = 0; + + dis.IffFundamentalData.prototype.initFromBinary = function(inputStream) + { + this.systemStatus = inputStream.readUByte(); + this.alternateParameter4 = inputStream.readUByte(); + this.informationLayers = inputStream.readUByte(); + this.modifier = inputStream.readUByte(); + this.parameter1 = inputStream.readUShort(); + this.parameter2 = inputStream.readUShort(); + this.parameter3 = inputStream.readUShort(); + this.parameter4 = inputStream.readUShort(); + this.parameter5 = inputStream.readUShort(); + this.parameter6 = inputStream.readUShort(); + }; + + dis.IffFundamentalData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemStatus); + outputStream.writeUByte(this.alternateParameter4); + outputStream.writeUByte(this.informationLayers); + outputStream.writeUByte(this.modifier); + outputStream.writeUShort(this.parameter1); + outputStream.writeUShort(this.parameter2); + outputStream.writeUShort(this.parameter3); + outputStream.writeUShort(this.parameter4); + outputStream.writeUShort(this.parameter5); + outputStream.writeUShort(this.parameter6); + }; +}; // end of class + + // node.js module support +exports.IffFundamentalData = dis.IffFundamentalData; + +// End of IffFundamentalData class + +/** + * 5.2.46. Intercom communcations parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomCommunicationsParameters = function() +{ + /** Type of intercom parameters record */ + this.recordType = 0; + + /** length of record-specifid field, in octets */ + this.recordLength = 0; + + /** variable length variablelist of data parameters */ + this.parameterValues = new Array(); + + dis.IntercomCommunicationsParameters.prototype.initFromBinary = function(inputStream) + { + this.recordType = inputStream.readUShort(); + this.recordLength = inputStream.readUShort(); + for(var idx = 0; idx < this.recordLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.parameterValues.push(anX); + } + + }; + + dis.IntercomCommunicationsParameters.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.recordType); + outputStream.writeUShort(this.recordLength); + for(var idx = 0; idx < this.parameterValues.length; idx++) + { + parameterValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomCommunicationsParameters = dis.IntercomCommunicationsParameters; + +// End of IntercomCommunicationsParameters class + +/** + * Section 5.3.8.5. Detailed inofrmation about the state of an intercom device and the actions it is requestion of another intercom device, or the response to a requested action. Required manual intervention to fix the intercom parameters, which can be of varialbe length. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomControlPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 32; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** control type */ + this.controlType = 0; + + /** control type */ + this.communicationsChannelType = 0; + + /** Source entity ID */ + this.sourceEntityID = new dis.EntityID(); + + /** The specific intercom device being simulated within an entity. */ + this.sourceCommunicationsDeviceID = 0; + + /** Line number to which the intercom control refers */ + this.sourceLineID = 0; + + /** priority of this message relative to transmissons from other intercom devices */ + this.transmitPriority = 0; + + /** current transmit state of the line */ + this.transmitLineState = 0; + + /** detailed type requested. */ + this.command = 0; + + /** eid of the entity that has created this intercom channel. */ + this.masterEntityID = new dis.EntityID(); + + /** specific intercom device that has created this intercom channel */ + this.masterCommunicationsDeviceID = 0; + + /** number of intercom parameters */ + this.intercomParametersLength = 0; + + /** Must be */ + this.intercomParameters = new Array(); + + dis.IntercomControlPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.controlType = inputStream.readUByte(); + this.communicationsChannelType = inputStream.readUByte(); + this.sourceEntityID.initFromBinary(inputStream); + this.sourceCommunicationsDeviceID = inputStream.readUByte(); + this.sourceLineID = inputStream.readUByte(); + this.transmitPriority = inputStream.readUByte(); + this.transmitLineState = inputStream.readUByte(); + this.command = inputStream.readUByte(); + this.masterEntityID.initFromBinary(inputStream); + this.masterCommunicationsDeviceID = inputStream.readUShort(); + this.intercomParametersLength = inputStream.readUInt(); + for(var idx = 0; idx < this.intercomParametersLength; idx++) + { + var anX = new dis.IntercomCommunicationsParameters(); + anX.initFromBinary(inputStream); + this.intercomParameters.push(anX); + } + + }; + + dis.IntercomControlPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUByte(this.controlType); + outputStream.writeUByte(this.communicationsChannelType); + this.sourceEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.sourceCommunicationsDeviceID); + outputStream.writeUByte(this.sourceLineID); + outputStream.writeUByte(this.transmitPriority); + outputStream.writeUByte(this.transmitLineState); + outputStream.writeUByte(this.command); + this.masterEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.masterCommunicationsDeviceID); + outputStream.writeUInt(this.intercomParametersLength); + for(var idx = 0; idx < this.intercomParameters.length; idx++) + { + intercomParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomControlPdu = dis.IntercomControlPdu; + +// End of IntercomControlPdu class + +/** + * Section 5.3.8.4. Actual transmission of intercome voice data. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomSignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 31; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entitythat is the source of the communication */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.communicationsDeviceID = 0; + + /** encoding scheme */ + this.encodingScheme = 0; + + /** tactical data link type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** data length, in bits */ + this.dataLength = 0; + + /** samples */ + this.samples = 0; + + /** data bytes */ + this.data = new Array(); + + dis.IntercomSignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.communicationsDeviceID = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.IntercomSignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.communicationsDeviceID); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomSignalPdu = dis.IntercomSignalPdu; + +// End of IntercomSignalPdu class + +/** + * Section 5.3.9.2 Information about a particular group of entities grouped together for the purposes of netowrk bandwidth reduction or aggregation. Needs manual cleanup. The GED size requires a database lookup. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsGroupOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 34; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.groupEntityID = new dis.EntityID(); + + /** type of entities constituting the group */ + this.groupedEntityCategory = 0; + + /** Number of individual entities constituting the group */ + this.numberOfGroupedEntities = 0; + + /** padding */ + this.pad2 = 0; + + /** latitude */ + this.latitude = 0; + + /** longitude */ + this.longitude = 0; + + /** GED records about each individual entity in the group. ^^^this is wrong--need a database lookup to find the actual size of the list elements */ + this.groupedEntityDescriptions = new Array(); + + dis.IsGroupOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.groupEntityID.initFromBinary(inputStream); + this.groupedEntityCategory = inputStream.readUByte(); + this.numberOfGroupedEntities = inputStream.readUByte(); + this.pad2 = inputStream.readUInt(); + this.latitude = inputStream.readFloat64(); + this.longitude = inputStream.readFloat64(); + for(var idx = 0; idx < this.numberOfGroupedEntities; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.groupedEntityDescriptions.push(anX); + } + + }; + + dis.IsGroupOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.groupEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.groupedEntityCategory); + outputStream.writeUByte(this.numberOfGroupedEntities); + outputStream.writeUInt(this.pad2); + outputStream.writeFloat64(this.latitude); + outputStream.writeFloat64(this.longitude); + for(var idx = 0; idx < this.groupedEntityDescriptions.length; idx++) + { + groupedEntityDescriptions[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IsGroupOfPdu = dis.IsGroupOfPdu; + +// End of IsGroupOfPdu class + +/** + * Section 5.3.9.4 The joining of two or more simulation entities is communicated by this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsPartOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 36; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating PDU */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving PDU */ + this.receivingEntityID = new dis.EntityID(); + + /** relationship of joined parts */ + this.relationship = new dis.Relationship(); + + /** location of part; centroid of part in host's coordinate system. x=range, y=bearing, z=0 */ + this.partLocation = new dis.Vector3Float(); + + /** named location */ + this.namedLocationID = new dis.NamedLocation(); + + /** entity type */ + this.partEntityType = new dis.EntityType(); + + dis.IsPartOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.relationship.initFromBinary(inputStream); + this.partLocation.initFromBinary(inputStream); + this.namedLocationID.initFromBinary(inputStream); + this.partEntityType.initFromBinary(inputStream); + }; + + dis.IsPartOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.relationship.encodeToBinary(outputStream); + this.partLocation.encodeToBinary(outputStream); + this.namedLocationID.encodeToBinary(outputStream); + this.partEntityType.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IsPartOfPdu = dis.IsPartOfPdu; + +// End of IsPartOfPdu class + +/** + * 5.2.47. Layer header. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LayerHeader = function() +{ + /** Layer number */ + this.layerNumber = 0; + + /** Layer speccific information enumeration */ + this.layerSpecificInformaiton = 0; + + /** information length */ + this.length = 0; + + dis.LayerHeader.prototype.initFromBinary = function(inputStream) + { + this.layerNumber = inputStream.readUByte(); + this.layerSpecificInformaiton = inputStream.readUByte(); + this.length = inputStream.readUShort(); + }; + + dis.LayerHeader.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.layerNumber); + outputStream.writeUByte(this.layerSpecificInformaiton); + outputStream.writeUShort(this.length); + }; +}; // end of class + + // node.js module support +exports.LayerHeader = dis.LayerHeader; + +// End of LayerHeader class + +/** + * Section 5.3.11.4: Information abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point and has size or orientation. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 44; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** number of linear segment parameters */ + this.numberOfSegments = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Linear segment parameters */ + this.linearSegmentParameters = new Array(); + + dis.LinearObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfSegments = inputStream.readUByte(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.objectType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSegments; idx++) + { + var anX = new dis.LinearSegmentParameter(); + anX.initFromBinary(inputStream); + this.linearSegmentParameters.push(anX); + } + + }; + + dis.LinearObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfSegments); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + this.objectType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.linearSegmentParameters.length; idx++) + { + linearSegmentParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.LinearObjectStatePdu = dis.LinearObjectStatePdu; + +// End of LinearObjectStatePdu class + +/** + * 5.2.48: Linear segment parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearSegmentParameter = function() +{ + /** number of segments */ + this.segmentNumber = 0; + + /** segment appearance */ + this.segmentAppearance = new dis.SixByteChunk(); + + /** location */ + this.location = new dis.Vector3Double(); + + /** orientation */ + this.orientation = new dis.Orientation(); + + /** segmentLength */ + this.segmentLength = 0; + + /** segmentWidth */ + this.segmentWidth = 0; + + /** segmentHeight */ + this.segmentHeight = 0; + + /** segment Depth */ + this.segmentDepth = 0; + + /** segment Depth */ + this.pad1 = 0; + + dis.LinearSegmentParameter.prototype.initFromBinary = function(inputStream) + { + this.segmentNumber = inputStream.readUByte(); + this.segmentAppearance.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.segmentLength = inputStream.readUShort(); + this.segmentWidth = inputStream.readUShort(); + this.segmentHeight = inputStream.readUShort(); + this.segmentDepth = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + }; + + dis.LinearSegmentParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.segmentNumber); + this.segmentAppearance.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.segmentLength); + outputStream.writeUShort(this.segmentWidth); + outputStream.writeUShort(this.segmentHeight); + outputStream.writeUShort(this.segmentDepth); + outputStream.writeUInt(this.pad1); + }; +}; // end of class + + // node.js module support +exports.LinearSegmentParameter = dis.LinearSegmentParameter; + +// End of LinearSegmentParameter class + +/** + * Section 5.3.5. Abstract superclass for logistics PDUs. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LogisticsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.LogisticsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.LogisticsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.LogisticsFamilyPdu = dis.LogisticsFamilyPdu; + +// End of LogisticsFamilyPdu class + +/** + * Section 5.2.15. Specifies the character set used inthe first byte, followed by 11 characters of text data. + * The generated Marking class should be augmented with a patch that adds getMarking() and + * setMarking() methods that convert between arrays and strings, and clamp the length + * of the string to 11 characters. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Marking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.Marking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 11; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.Marking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 11; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; + + /* + * Returns the byte array marking, in string format. + * @return string format marking characters + */ + dis.Marking.prototype.getMarking = function() + { + var marking = ""; + for(var idx = 0; idx < 11; idx++) + { + marking = marking + String.fromCharCode(this.characters[idx]); + } + + return marking; + }; + + /** + * Given a string format marking, sets the bytes of the marking object + * to the appropriate character values. Clamps the string to no more + * than 11 characters. + * + * @param {String} newMarking string format marking + * @returns {nothing} + */ + dis.Marking.prototype.setMarking = function(newMarking) + { + var stringLen = newMarking.length; + if(stringLen > 11) + stringLen = 11; + + // Copy over up to 11 characters from the string to the array + var charsCopied = 0; + while(charsCopied < stringLen) + { + this.characters[charsCopied] = newMarking.charCodeAt( charsCopied ); + charsCopied++; + } + + // Zero-fill the remainer of the character array + while(charsCopied < 11) + { + this.characters[ charsCopied ] = 0; + charsCopied++; + } + + }; +}; // end of class + + // node.js module support +exports.Marking = dis.Marking; + +// End of Marking class + +/** + * Section 5.3.10.3 Information about individual mines within a minefield. This is very, very wrong. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 39; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** ID of entity making request */ + this.requestingEntityID = new dis.EntityID(); + + /** Minefield sequence number */ + this.minefieldSequenceNumbeer = 0; + + /** request ID */ + this.requestID = 0; + + /** pdu sequence number */ + this.pduSequenceNumber = 0; + + /** number of pdus in response */ + this.numberOfPdus = 0; + + /** how many mines are in this PDU */ + this.numberOfMinesInThisPdu = 0; + + /** how many sensor type are in this PDU */ + this.numberOfSensorTypes = 0; + + /** padding */ + this.pad2 = 0; + + /** 32 boolean fields */ + this.dataFilter = 0; + + /** Mine type */ + this.mineType = new dis.EntityType(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + /** Padding to get things 32-bit aligned. ^^^this is wrong--dyanmically sized padding needed */ + this.pad3 = 0; + + /** Mine locations */ + this.mineLocation = new Array(); + + dis.MinefieldDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.minefieldSequenceNumbeer = inputStream.readUShort(); + this.requestID = inputStream.readUByte(); + this.pduSequenceNumber = inputStream.readUByte(); + this.numberOfPdus = inputStream.readUByte(); + this.numberOfMinesInThisPdu = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.mineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + this.pad3 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMinesInThisPdu; idx++) + { + var anX = new dis.Vector3Float(); + anX.initFromBinary(inputStream); + this.mineLocation.push(anX); + } + + }; + + dis.MinefieldDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequenceNumbeer); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.pduSequenceNumber); + outputStream.writeUByte(this.numberOfPdus); + outputStream.writeUByte(this.numberOfMinesInThisPdu); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.dataFilter); + this.mineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad3); + for(var idx = 0; idx < this.mineLocation.length; idx++) + { + mineLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldDataPdu = dis.MinefieldDataPdu; + +// End of MinefieldDataPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.MinefieldFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.MinefieldFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.MinefieldFamilyPdu = dis.MinefieldFamilyPdu; + +// End of MinefieldFamilyPdu class + +/** + * Section 5.3.10.2 Query a minefield for information about individual mines. Requires manual clean up to get the padding right. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 38; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** EID of entity making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** Number of perimeter points for the minefield */ + this.numberOfPerimeterPoints = 0; + + /** Padding */ + this.pad2 = 0; + + /** Number of sensor types */ + this.numberOfSensorTypes = 0; + + /** data filter, 32 boolean fields */ + this.dataFilter = 0; + + /** Entity type of mine being requested */ + this.requestedMineType = new dis.EntityType(); + + /** perimeter points of request */ + this.requestedPerimeterPoints = new Array(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + dis.MinefieldQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.requestedMineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.requestedPerimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + }; + + dis.MinefieldQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + outputStream.writeUByte(this.pad2); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUInt(this.dataFilter); + this.requestedMineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.requestedPerimeterPoints.length; idx++) + { + requestedPerimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldQueryPdu = dis.MinefieldQueryPdu; + +// End of MinefieldQueryPdu class + +/** + * Section 5.3.10.4 proivde the means to request a retransmit of a minefield data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldResponseNackPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 40; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** entity ID making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** how many pdus were missing */ + this.numberOfMissingPdus = 0; + + /** PDU sequence numbers that were missing */ + this.missingPduSequenceNumbers = new Array(); + + dis.MinefieldResponseNackPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfMissingPdus = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMissingPdus; idx++) + { + var anX = new dis.EightByteChunk(); + anX.initFromBinary(inputStream); + this.missingPduSequenceNumbers.push(anX); + } + + }; + + dis.MinefieldResponseNackPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfMissingPdus); + for(var idx = 0; idx < this.missingPduSequenceNumbers.length; idx++) + { + missingPduSequenceNumbers[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldResponseNackPdu = dis.MinefieldResponseNackPdu; + +// End of MinefieldResponseNackPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 37; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** Minefield sequence */ + this.minefieldSequence = 0; + + /** force ID */ + this.forceID = 0; + + /** Number of permieter points */ + this.numberOfPerimeterPoints = 0; + + /** type of minefield */ + this.minefieldType = new dis.EntityType(); + + /** how many mine types */ + this.numberOfMineTypes = 0; + + /** location of minefield in world coords */ + this.minefieldLocation = new dis.Vector3Double(); + + /** orientation of minefield */ + this.minefieldOrientation = new dis.Orientation(); + + /** appearance bitflags */ + this.appearance = 0; + + /** protocolMode */ + this.protocolMode = 0; + + /** perimeter points for the minefield */ + this.perimeterPoints = new Array(); + + /** Type of mines */ + this.mineType = new Array(); + + dis.MinefieldStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.minefieldSequence = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.minefieldType.initFromBinary(inputStream); + this.numberOfMineTypes = inputStream.readUShort(); + this.minefieldLocation.initFromBinary(inputStream); + this.minefieldOrientation.initFromBinary(inputStream); + this.appearance = inputStream.readUShort(); + this.protocolMode = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.perimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfMineTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.mineType.push(anX); + } + + }; + + dis.MinefieldStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequence); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + this.minefieldType.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfMineTypes); + this.minefieldLocation.encodeToBinary(outputStream); + this.minefieldOrientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.appearance); + outputStream.writeUShort(this.protocolMode); + for(var idx = 0; idx < this.perimeterPoints.length; idx++) + { + perimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.mineType.length; idx++) + { + mineType[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldStatePdu = dis.MinefieldStatePdu; + +// End of MinefieldStatePdu class + +/** + * Radio modulation + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ModulationType = function() +{ + /** spread spectrum, 16 bit boolean array */ + this.spreadSpectrum = 0; + + /** major */ + this.major = 0; + + /** detail */ + this.detail = 0; + + /** system */ + this.system = 0; + + dis.ModulationType.prototype.initFromBinary = function(inputStream) + { + this.spreadSpectrum = inputStream.readUShort(); + this.major = inputStream.readUShort(); + this.detail = inputStream.readUShort(); + this.system = inputStream.readUShort(); + }; + + dis.ModulationType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.spreadSpectrum); + outputStream.writeUShort(this.major); + outputStream.writeUShort(this.detail); + outputStream.writeUShort(this.system); + }; +}; // end of class + + // node.js module support +exports.ModulationType = dis.ModulationType; + +// End of ModulationType class + +/** + * discrete ostional relationsihip + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.NamedLocation = function() +{ + /** station name enumeration */ + this.stationName = 0; + + /** station number */ + this.stationNumber = 0; + + dis.NamedLocation.prototype.initFromBinary = function(inputStream) + { + this.stationName = inputStream.readUShort(); + this.stationNumber = inputStream.readUShort(); + }; + + dis.NamedLocation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.stationName); + outputStream.writeUShort(this.stationNumber); + }; +}; // end of class + + // node.js module support +exports.NamedLocation = dis.NamedLocation; + +// End of NamedLocation class + +/** + * Identifies type of object. This is a shorter version of EntityType that omits the specific and extra fields. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ObjectType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + dis.ObjectType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + }; + + dis.ObjectType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + }; +}; // end of class + + // node.js module support +exports.ObjectType = dis.ObjectType; + +// End of ObjectType class + +/** + * 8 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.OneByteChunk = function() +{ + /** one byte of arbitrary data */ + this.otherParameters = new Array(0); + + dis.OneByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 1; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.OneByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 1; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.OneByteChunk = dis.OneByteChunk; + +// End of OneByteChunk class + +/** + * Section 5.2.17. Three floating point values representing an orientation, psi, theta, and phi, aka the euler angles, in radians + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Orientation = function() +{ + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + dis.Orientation.prototype.initFromBinary = function(inputStream) + { + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + }; + + dis.Orientation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + }; +}; // end of class + + // node.js module support +exports.Orientation = dis.Orientation; + +// End of Orientation class + +/** + * The superclass for all PDUs. This incorporates the PduHeader record, section 5.2.29. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 0; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.Pdu = dis.Pdu; + +// End of Pdu class + +/** + * A container that holds PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduContainer = function() +{ + /** Number of PDUs in the container list */ + this.numberOfPdus = 0; + + /** List of PDUs */ + this.pdus = new Array(); + + dis.PduContainer.prototype.initFromBinary = function(inputStream) + { + this.numberOfPdus = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfPdus; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdus.push(anX); + } + + }; + + dis.PduContainer.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.numberOfPdus); + for(var idx = 0; idx < this.pdus.length; idx++) + { + pdus[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduContainer = dis.PduContainer; + +// End of PduContainer class + +/** + * Non-DIS class, used to describe streams of PDUs when logging to SQL databases + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduStream = function() +{ + /** short description of this PDU stream */ + this.shortDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Longish description of this PDU stream */ + this.longDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Name of person performing recording */ + this.personRecording = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Email of person performing recording */ + this.authorEmail = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Start time of recording, in Unix time */ + this.startTime = 0; + + /** stop time of recording, in Unix time */ + this.stopTime = 0; + + /** how many PDUs in this stream */ + this.pduCount = 0; + + /** variable length list of PDUs */ + this.pdusInStream = new Array(); + + dis.PduStream.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 256; idx++) + { + this.shortDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 512; idx++) + { + this.longDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.personRecording[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.authorEmail[ idx ] = inputStream.readByte(); + } + this.startTime = inputStream.readLong(); + this.stopTime = inputStream.readLong(); + this.pduCount = inputStream.readUInt(); + for(var idx = 0; idx < this.pduCount; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdusInStream.push(anX); + } + + }; + + dis.PduStream.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 256; idx++) + { + outputStream.writeByte(this.shortDescription[ idx ] ); + } + for(var idx = 0; idx < 512; idx++) + { + outputStream.writeByte(this.longDescription[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.personRecording[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.authorEmail[ idx ] ); + } + outputStream.writeLong(this.startTime); + outputStream.writeLong(this.stopTime); + outputStream.writeUInt(this.pduCount); + for(var idx = 0; idx < this.pdusInStream.length; idx++) + { + pdusInStream[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduStream = dis.PduStream; + +// End of PduStream class + +/** + * x,y point + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Point = function() +{ + /** x */ + this.x = 0; + + /** y */ + this.y = 0; + + dis.Point.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + }; + + dis.Point.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + }; +}; // end of class + + // node.js module support +exports.Point = dis.Point; + +// End of Point class + +/** + * Section 5.3.11.3: Inormation abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PointObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 43; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Object location */ + this.objectLocation = new dis.Vector3Double(); + + /** Object orientation */ + this.objectOrientation = new dis.Orientation(); + + /** Object apperance */ + this.objectAppearance = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** padding */ + this.pad2 = 0; + + dis.PointObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectLocation.initFromBinary(inputStream); + this.objectOrientation.initFromBinary(inputStream); + this.objectAppearance = inputStream.readFloat64(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.pad2 = inputStream.readUInt(); + }; + + dis.PointObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectLocation.encodeToBinary(outputStream); + this.objectOrientation.encodeToBinary(outputStream); + outputStream.writeFloat64(this.objectAppearance); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + outputStream.writeUInt(this.pad2); + }; +}; // end of class + + // node.js module support +exports.PointObjectStatePdu = dis.PointObjectStatePdu; + +// End of PointObjectStatePdu class + +/** + * Data about a propulsion system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PropulsionSystemData = function() +{ + /** powerSetting */ + this.powerSetting = 0; + + /** engine RPMs */ + this.engineRpm = 0; + + dis.PropulsionSystemData.prototype.initFromBinary = function(inputStream) + { + this.powerSetting = inputStream.readFloat32(); + this.engineRpm = inputStream.readFloat32(); + }; + + dis.PropulsionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.powerSetting); + outputStream.writeFloat32(this.engineRpm); + }; +}; // end of class + + // node.js module support +exports.PropulsionSystemData = dis.PropulsionSystemData; + +// End of PropulsionSystemData class + +/** + * Section 5.3.8. Abstract superclass for radio communications PDUs. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioCommunicationsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.RadioCommunicationsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.RadioCommunicationsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.RadioCommunicationsFamilyPdu = dis.RadioCommunicationsFamilyPdu; + +// End of RadioCommunicationsFamilyPdu class + +/** + * Section 5.2.25. Identifies the type of radio + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioEntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** specific info based on subcategory field */ + this.nomenclatureVersion = 0; + + this.nomenclature = 0; + + dis.RadioEntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.nomenclatureVersion = inputStream.readUByte(); + this.nomenclature = inputStream.readUShort(); + }; + + dis.RadioEntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.nomenclatureVersion); + outputStream.writeUShort(this.nomenclature); + }; +}; // end of class + + // node.js module support +exports.RadioEntityType = dis.RadioEntityType; + +// End of RadioEntityType class + +/** + * Section 5.3.8.3. Communication of a receiver state. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ReceiverPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 27; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.receiverState = 0; + + /** padding */ + this.padding1 = 0; + + /** received power */ + this.receivedPower = 0; + + /** ID of transmitter */ + this.transmitterEntityId = new dis.EntityID(); + + /** ID of transmitting radio */ + this.transmitterRadioId = 0; + + dis.ReceiverPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.receiverState = inputStream.readUShort(); + this.padding1 = inputStream.readUShort(); + this.receivedPower = inputStream.readFloat32(); + this.transmitterEntityId.initFromBinary(inputStream); + this.transmitterRadioId = inputStream.readUShort(); + }; + + dis.ReceiverPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.receiverState); + outputStream.writeUShort(this.padding1); + outputStream.writeFloat32(this.receivedPower); + this.transmitterEntityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.transmitterRadioId); + }; +}; // end of class + + // node.js module support +exports.ReceiverPdu = dis.ReceiverPdu; + +// End of ReceiverPdu class + +/** + * Section 5.3.12.13: A request for one or more records of data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 65; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** event type */ + this.eventType = 0; + + /** time */ + this.time = 0; + + /** numberOfRecords */ + this.numberOfRecords = 0; + + /** record IDs */ + this.recordIDs = new Array(); + + dis.RecordQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.eventType = inputStream.readUShort(); + this.time = inputStream.readUInt(); + this.numberOfRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecords; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.recordIDs.push(anX); + } + + }; + + dis.RecordQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.time); + outputStream.writeUInt(this.numberOfRecords); + for(var idx = 0; idx < this.recordIDs.length; idx++) + { + recordIDs[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.RecordQueryReliablePdu = dis.RecordQueryReliablePdu; + +// End of RecordQueryReliablePdu class + +/** + * Record sets, used in transfer control request PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordSet = function() +{ + /** record ID */ + this.recordID = 0; + + /** record set serial number */ + this.recordSetSerialNumber = 0; + + /** record length */ + this.recordLength = 0; + + /** record count */ + this.recordCount = 0; + + /** ^^^This is wrong--variable sized data records */ + this.recordValues = 0; + + /** ^^^This is wrong--variable sized padding */ + this.pad4 = 0; + + dis.RecordSet.prototype.initFromBinary = function(inputStream) + { + this.recordID = inputStream.readUInt(); + this.recordSetSerialNumber = inputStream.readUInt(); + this.recordLength = inputStream.readUShort(); + this.recordCount = inputStream.readUShort(); + this.recordValues = inputStream.readUShort(); + this.pad4 = inputStream.readUByte(); + }; + + dis.RecordSet.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.recordID); + outputStream.writeUInt(this.recordSetSerialNumber); + outputStream.writeUShort(this.recordLength); + outputStream.writeUShort(this.recordCount); + outputStream.writeUShort(this.recordValues); + outputStream.writeUByte(this.pad4); + }; +}; // end of class + + // node.js module support +exports.RecordSet = dis.RecordSet; + +// End of RecordSet class + +/** + * 5.2.56. Purpose for joinging two entities + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Relationship = function() +{ + /** Nature of join */ + this.nature = 0; + + /** position of join */ + this.position = 0; + + dis.Relationship.prototype.initFromBinary = function(inputStream) + { + this.nature = inputStream.readUShort(); + this.position = inputStream.readUShort(); + }; + + dis.Relationship.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.nature); + outputStream.writeUShort(this.position); + }; +}; // end of class + + // node.js module support +exports.Relationship = dis.Relationship; + +// End of Relationship class + +/** + * Section 5.3.6.2. Remove an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 12; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.RemoveEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityPdu = dis.RemoveEntityPdu; + +// End of RemoveEntityPdu class + +/** + * Section 5.3.12.2: Removal of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 52; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.RemoveEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityReliablePdu = dis.RemoveEntityReliablePdu; + +// End of RemoveEntityReliablePdu class + +/** + * Section 5.2.5.5. Repair is complete. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairCompletePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 9; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Enumeration for type of repair */ + this.repair = 0; + + /** padding, number prevents conflict with superclass ivar name */ + this.padding2 = 0; + + dis.RepairCompletePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repair = inputStream.readUShort(); + this.padding2 = inputStream.readShort(); + }; + + dis.RepairCompletePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.repair); + outputStream.writeShort(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairCompletePdu = dis.RepairCompletePdu; + +// End of RepairCompletePdu class + +/** + * Section 5.2.5.6. Sent after repair complete PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 10; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Result of repair operation */ + this.repairResult = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + dis.RepairResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repairResult = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + }; + + dis.RepairResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.repairResult); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairResponsePdu = dis.RepairResponsePdu; + +// End of RepairResponsePdu class + +/** + * Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyCancelPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 8; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + dis.ResupplyCancelPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + }; + + dis.ResupplyCancelPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.ResupplyCancelPdu = dis.ResupplyCancelPdu; + +// End of ResupplyCancelPdu class + +/** + * Section 5.3.5.2. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyOfferPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 6; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyOfferPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyOfferPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyOfferPdu = dis.ResupplyOfferPdu; + +// End of ResupplyOfferPdu class + +/** + * Section 5.3.5.3. Receipt of supplies is communiated. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyReceivedPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 7; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyReceivedPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyReceivedPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyReceivedPdu = dis.ResupplyReceivedPdu; + +// End of ResupplyReceivedPdu class + +/** + * Section 5.3.7.5. SEES PDU, supplemental emissions entity state information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SeesPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 30; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Originating entity ID */ + this.orginatingEntityID = new dis.EntityID(); + + /** IR Signature representation index */ + this.infraredSignatureRepresentationIndex = 0; + + /** acoustic Signature representation index */ + this.acousticSignatureRepresentationIndex = 0; + + /** radar cross section representation index */ + this.radarCrossSectionSignatureRepresentationIndex = 0; + + /** how many propulsion systems */ + this.numberOfPropulsionSystems = 0; + + /** how many vectoring nozzle systems */ + this.numberOfVectoringNozzleSystems = 0; + + /** variable length list of propulsion system data */ + this.propulsionSystemData = new Array(); + + /** variable length list of vectoring system data */ + this.vectoringSystemData = new Array(); + + dis.SeesPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.infraredSignatureRepresentationIndex = inputStream.readUShort(); + this.acousticSignatureRepresentationIndex = inputStream.readUShort(); + this.radarCrossSectionSignatureRepresentationIndex = inputStream.readUShort(); + this.numberOfPropulsionSystems = inputStream.readUShort(); + this.numberOfVectoringNozzleSystems = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPropulsionSystems; idx++) + { + var anX = new dis.PropulsionSystemData(); + anX.initFromBinary(inputStream); + this.propulsionSystemData.push(anX); + } + + for(var idx = 0; idx < this.numberOfVectoringNozzleSystems; idx++) + { + var anX = new dis.VectoringNozzleSystemData(); + anX.initFromBinary(inputStream); + this.vectoringSystemData.push(anX); + } + + }; + + dis.SeesPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.infraredSignatureRepresentationIndex); + outputStream.writeUShort(this.acousticSignatureRepresentationIndex); + outputStream.writeUShort(this.radarCrossSectionSignatureRepresentationIndex); + outputStream.writeUShort(this.numberOfPropulsionSystems); + outputStream.writeUShort(this.numberOfVectoringNozzleSystems); + for(var idx = 0; idx < this.propulsionSystemData.length; idx++) + { + propulsionSystemData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.vectoringSystemData.length; idx++) + { + vectoringSystemData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SeesPdu = dis.SeesPdu; + +// End of SeesPdu class + +/** + * Section 5.3.5.1. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ServiceRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 5; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is requesting service */ + this.requestingEntityID = new dis.EntityID(); + + /** Entity that is providing the service */ + this.servicingEntityID = new dis.EntityID(); + + /** type of service requested */ + this.serviceTypeRequested = 0; + + /** How many requested */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.serviceRequestPadding = 0; + + this.supplies = new Array(); + + dis.ServiceRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.requestingEntityID.initFromBinary(inputStream); + this.servicingEntityID.initFromBinary(inputStream); + this.serviceTypeRequested = inputStream.readUByte(); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.serviceRequestPadding = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ServiceRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.requestingEntityID.encodeToBinary(outputStream); + this.servicingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.serviceTypeRequested); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.serviceRequestPadding); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ServiceRequestPdu = dis.ServiceRequestPdu; + +// End of ServiceRequestPdu class + +/** + * Section 5.3.6.9. Change state information with the data contained in this. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 19; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.SetDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.SetDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataPdu = dis.SetDataPdu; + +// End of SetDataPdu class + +/** + * Section 5.3.12.9: initializing or chaning internal state information, reliable. Needs manual intervention to fix padding on variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 59; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.SetDataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.SetDataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataReliablePdu = dis.SetDataReliablePdu; + +// End of SetDataReliablePdu class + +/** + * Section 5.3.12.14: Initializing or changing internal parameter info. Needs manual intervention to fix padding in recrod set PDUs. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetRecordReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 64; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Number of record sets in list */ + this.numberOfRecordSets = 0; + + /** record sets */ + this.recordSets = new Array(); + + dis.SetRecordReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfRecordSets = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.SetRecordReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetRecordReliablePdu = dis.SetRecordReliablePdu; + +// End of SetRecordReliablePdu class + +/** + * Shaft RPMs, used in underwater acoustic clacluations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ShaftRPMs = function() +{ + /** Current shaft RPMs */ + this.currentShaftRPMs = 0; + + /** ordered shaft rpms */ + this.orderedShaftRPMs = 0; + + /** rate of change of shaft RPMs */ + this.shaftRPMRateOfChange = 0; + + dis.ShaftRPMs.prototype.initFromBinary = function(inputStream) + { + this.currentShaftRPMs = inputStream.readShort(); + this.orderedShaftRPMs = inputStream.readShort(); + this.shaftRPMRateOfChange = inputStream.readFloat32(); + }; + + dis.ShaftRPMs.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeShort(this.currentShaftRPMs); + outputStream.writeShort(this.orderedShaftRPMs); + outputStream.writeFloat32(this.shaftRPMRateOfChange); + }; +}; // end of class + + // node.js module support +exports.ShaftRPMs = dis.ShaftRPMs; + +// End of ShaftRPMs class + +/** + * Section 5.3.8.2. Detailed information about a radio transmitter. This PDU requires manually written code to complete. The encodingScheme field can be used in multiple ways, which requires hand-written code to finish. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 26; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.encodingScheme = 0; + + /** tdl type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** length of data, in bits */ + this.dataLength = 0; + + /** number of samples. If the PDU contains encoded audio, this should be zero. */ + this.samples = 0; + + /** list of eight bit values. Must be padded to fall on a 32 bit boundary. */ + this.data = new Array(); + + dis.SignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.SignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SignalPdu = dis.SignalPdu; + +// End of SignalPdu class + +/** + * Section 5.2.14.1. A Simulation Address record shall consist of the Site Identification number and the Application Identification number. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationAddress = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + dis.SimulationAddress.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + }; + + dis.SimulationAddress.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + }; +}; // end of class + + // node.js module support +exports.SimulationAddress = dis.SimulationAddress; + +// End of SimulationAddress class + +/** + * Section 5.3.6. Abstract superclass for PDUs relating to the simulation itself. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementFamilyPdu = dis.SimulationManagementFamilyPdu; + +// End of SimulationManagementFamilyPdu class + +/** + * Section 5.3.12: Abstract superclass for reliable simulation management PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementWithReliabilityFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementWithReliabilityFamilyPdu = dis.SimulationManagementWithReliabilityFamilyPdu; + +// End of SimulationManagementWithReliabilityFamilyPdu class + +/** + * 48 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SixByteChunk = function() +{ + /** six bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0); + + dis.SixByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 6; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.SixByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 6; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.SixByteChunk = dis.SixByteChunk; + +// End of SixByteChunk class + +/** + * Section 5.2.4.3. Used when the antenna pattern type in the transmitter pdu is of value 2. Specified the direction and radiation pattern from a radio transmitter's antenna. NOTE: this class must be hand-coded to clean up some implementation details. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SphericalHarmonicAntennaPattern = function() +{ + this.harmonicOrder = 0; + + dis.SphericalHarmonicAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.harmonicOrder = inputStream.readByte(); + }; + + dis.SphericalHarmonicAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeByte(this.harmonicOrder); + }; +}; // end of class + + // node.js module support +exports.SphericalHarmonicAntennaPattern = dis.SphericalHarmonicAntennaPattern; + +// End of SphericalHarmonicAntennaPattern class + +/** + * Section 5.2.6.3. Start or resume an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 13; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall start or resume */ + this.realWorldTime = new dis.ClockTime(); + + /** Simulation clock time at which the simulation shall start or resume */ + this.simulationTime = new dis.ClockTime(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.StartResumePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumePdu = dis.StartResumePdu; + +// End of StartResumePdu class + +/** + * Section 5.3.12.3: Start resume simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 53; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** time in simulation for the simulation to resume */ + this.simulationTime = new dis.ClockTime(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StartResumeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumeReliablePdu = dis.StartResumeReliablePdu; + +// End of StartResumeReliablePdu class + +/** + * Section 5.2.3.4. Stop or freeze an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 14; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall stop or freeze */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason the simulation was stopped or frozen */ + this.reason = 0; + + /** Internal behavior of the simulation and its appearance while frozento the other participants */ + this.frozenBehavior = 0; + + /** padding */ + this.padding1 = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.StopFreezePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeShort(this.padding1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezePdu = dis.StopFreezePdu; + +// End of StopFreezePdu class + +/** + * Section 5.3.12.4: Stop freeze simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 54; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason for stopping/freezing simulation */ + this.reason = 0; + + /** internal behvior of the simulation while frozen */ + this.frozenBehavior = 0; + + /** reliablity level */ + this.requiredReliablityService = 0; + + /** padding */ + this.pad1 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StopFreezeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.requiredReliablityService = inputStream.readUByte(); + this.pad1 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeUByte(this.requiredReliablityService); + outputStream.writeUByte(this.pad1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezeReliablePdu = dis.StopFreezeReliablePdu; + +// End of StopFreezeReliablePdu class + +/** + * Section 5.2.30. A supply, and the amount of that supply. Similar to an entity kind but with the addition of a quantity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SupplyQuantity = function() +{ + /** Type of supply */ + this.supplyType = new dis.EntityType(); + + /** quantity to be supplied */ + this.quantity = 0; + + dis.SupplyQuantity.prototype.initFromBinary = function(inputStream) + { + this.supplyType.initFromBinary(inputStream); + this.quantity = inputStream.readUByte(); + }; + + dis.SupplyQuantity.prototype.encodeToBinary = function(outputStream) + { + this.supplyType.encodeToBinary(outputStream); + outputStream.writeUByte(this.quantity); + }; +}; // end of class + + // node.js module support +exports.SupplyQuantity = dis.SupplyQuantity; + +// End of SupplyQuantity class + +/** + * Section 5.3.11: Abstract superclass for synthetic environment PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SyntheticEnvironmentFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.SyntheticEnvironmentFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.SyntheticEnvironmentFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.SyntheticEnvironmentFamilyPdu = dis.SyntheticEnvironmentFamilyPdu; + +// End of SyntheticEnvironmentFamilyPdu class + +/** + * 5.2.58. Used in IFF ATC PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SystemID = function() +{ + /** System Type */ + this.systemType = 0; + + /** System name, an enumeration */ + this.systemName = 0; + + /** System mode */ + this.systemMode = 0; + + /** Change Options */ + this.changeOptions = 0; + + dis.SystemID.prototype.initFromBinary = function(inputStream) + { + this.systemType = inputStream.readUShort(); + this.systemName = inputStream.readUShort(); + this.systemMode = inputStream.readUByte(); + this.changeOptions = inputStream.readUByte(); + }; + + dis.SystemID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.systemType); + outputStream.writeUShort(this.systemName); + outputStream.writeUByte(this.systemMode); + outputStream.writeUByte(this.changeOptions); + }; +}; // end of class + + // node.js module support +exports.SystemID = dis.SystemID; + +// End of SystemID class + +/** + * One track/jam target + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TrackJamTarget = function() +{ + /** track/jam target */ + this.trackJam = new dis.EntityID(); + + /** Emitter ID */ + this.emitterID = 0; + + /** beam ID */ + this.beamID = 0; + + dis.TrackJamTarget.prototype.initFromBinary = function(inputStream) + { + this.trackJam.initFromBinary(inputStream); + this.emitterID = inputStream.readUByte(); + this.beamID = inputStream.readUByte(); + }; + + dis.TrackJamTarget.prototype.encodeToBinary = function(outputStream) + { + this.trackJam.encodeToBinary(outputStream); + outputStream.writeUByte(this.emitterID); + outputStream.writeUByte(this.beamID); + }; +}; // end of class + + // node.js module support +exports.TrackJamTarget = dis.TrackJamTarget; + +// End of TrackJamTarget class + +/** + * Section 5.3.9.3 Information initiating the dyanic allocation and control of simulation entities between two simulation applications. Requires manual cleanup. The padding between record sets is variable. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransferControlRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 35; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating request */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving request */ + this.recevingEntityID = new dis.EntityID(); + + /** ID ofrequest */ + this.requestID = 0; + + /** required level of reliabliity service. */ + this.requiredReliabilityService = 0; + + /** type of transfer desired */ + this.tranferType = 0; + + /** The entity for which control is being requested to transfer */ + this.transferEntityID = new dis.EntityID(); + + /** number of record sets to transfer */ + this.numberOfRecordSets = 0; + + /** ^^^This is wrong--the RecordSet class needs more work */ + this.recordSets = new Array(); + + dis.TransferControlRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.recevingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.tranferType = inputStream.readUByte(); + this.transferEntityID.initFromBinary(inputStream); + this.numberOfRecordSets = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.TransferControlRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.recevingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUByte(this.tranferType); + this.transferEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransferControlRequestPdu = dis.TransferControlRequestPdu; + +// End of TransferControlRequestPdu class + +/** + * Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete, since the modulation parameters are of variable length. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransmitterPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 25; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** linear accelleration of entity */ + this.radioEntityType = new dis.RadioEntityType(); + + /** transmit state */ + this.transmitState = 0; + + /** input source */ + this.inputSource = 0; + + /** padding */ + this.padding1 = 0; + + /** Location of antenna */ + this.antennaLocation = new dis.Vector3Double(); + + /** relative location of antenna, in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + /** antenna pattern type */ + this.antennaPatternType = 0; + + /** atenna pattern length */ + this.antennaPatternCount = 0; + + /** frequency */ + this.frequency = 0; + + /** transmit frequency Bandwidth */ + this.transmitFrequencyBandwidth = 0; + + /** transmission power */ + this.power = 0; + + /** modulation */ + this.modulationType = new dis.ModulationType(); + + /** crypto system enumeration */ + this.cryptoSystem = 0; + + /** crypto system key identifer */ + this.cryptoKeyId = 0; + + /** how many modulation parameters we have */ + this.modulationParameterCount = 0; + + /** padding2 */ + this.padding2 = 0; + + /** padding3 */ + this.padding3 = 0; + + /** variable length list of modulation parameters */ + this.modulationParametersList = new Array(); + + /** variable length list of antenna pattern records */ + this.antennaPatternList = new Array(); + + dis.TransmitterPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.radioEntityType.initFromBinary(inputStream); + this.transmitState = inputStream.readUByte(); + this.inputSource = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + this.antennaPatternType = inputStream.readUShort(); + this.antennaPatternCount = inputStream.readUShort(); + this.frequency = inputStream.readLong(); + this.transmitFrequencyBandwidth = inputStream.readFloat32(); + this.power = inputStream.readFloat32(); + this.modulationType.initFromBinary(inputStream); + this.cryptoSystem = inputStream.readUShort(); + this.cryptoKeyId = inputStream.readUShort(); + this.modulationParameterCount = inputStream.readUByte(); + this.padding2 = inputStream.readUShort(); + this.padding3 = inputStream.readUByte(); + for(var idx = 0; idx < this.modulationParameterCount; idx++) + { + var anX = new dis.ModulationType(); + anX.initFromBinary(inputStream); + this.modulationParametersList.push(anX); + } + + for(var idx = 0; idx < this.antennaPatternCount; idx++) + { + var anX = new dis.BeamAntennaPattern(); + anX.initFromBinary(inputStream); + this.antennaPatternList.push(anX); + } + + }; + + dis.TransmitterPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + this.radioEntityType.encodeToBinary(outputStream); + outputStream.writeUByte(this.transmitState); + outputStream.writeUByte(this.inputSource); + outputStream.writeUShort(this.padding1); + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + outputStream.writeUShort(this.antennaPatternType); + outputStream.writeUShort(this.antennaPatternCount); + outputStream.writeLong(this.frequency); + outputStream.writeFloat32(this.transmitFrequencyBandwidth); + outputStream.writeFloat32(this.power); + this.modulationType.encodeToBinary(outputStream); + outputStream.writeUShort(this.cryptoSystem); + outputStream.writeUShort(this.cryptoKeyId); + outputStream.writeUByte(this.modulationParameterCount); + outputStream.writeUShort(this.padding2); + outputStream.writeUByte(this.padding3); + for(var idx = 0; idx < this.modulationParametersList.length; idx++) + { + modulationParametersList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.antennaPatternList.length; idx++) + { + antennaPatternList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransmitterPdu = dis.TransmitterPdu; + +// End of TransmitterPdu class + +/** + * 16 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TwoByteChunk = function() +{ + /** two bytes of arbitrary data */ + this.otherParameters = new Array(0, 0); + + dis.TwoByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 2; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.TwoByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 2; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.TwoByteChunk = dis.TwoByteChunk; + +// End of TwoByteChunk class + +/** + * Section 5.3.7.3. Information about underwater acoustic emmissions. This requires manual cleanup. The beam data records should ALL be a the finish, rather than attached to each emitter system. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UaPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 29; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emission */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU */ + this.stateChangeIndicator = 0; + + /** padding */ + this.pad = 0; + + /** This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. */ + this.passiveParameterIndex = 0; + + /** This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. */ + this.propulsionPlantConfiguration = 0; + + /** This field shall represent the number of shafts on a platform */ + this.numberOfShafts = 0; + + /** This field shall indicate the number of APAs described in the current UA PDU */ + this.numberOfAPAs = 0; + + /** This field shall specify the number of UA emitter systems being described in the current UA PDU */ + this.numberOfUAEmitterSystems = 0; + + /** shaft RPM values */ + this.shaftRPMs = new Array(); + + /** apaData */ + this.apaData = new Array(); + + this.emitterSystems = new Array(); + + dis.UaPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateChangeIndicator = inputStream.readByte(); + this.pad = inputStream.readByte(); + this.passiveParameterIndex = inputStream.readUShort(); + this.propulsionPlantConfiguration = inputStream.readUByte(); + this.numberOfShafts = inputStream.readUByte(); + this.numberOfAPAs = inputStream.readUByte(); + this.numberOfUAEmitterSystems = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfShafts; idx++) + { + var anX = new dis.ShaftRPMs(); + anX.initFromBinary(inputStream); + this.shaftRPMs.push(anX); + } + + for(var idx = 0; idx < this.numberOfAPAs; idx++) + { + var anX = new dis.ApaData(); + anX.initFromBinary(inputStream); + this.apaData.push(anX); + } + + for(var idx = 0; idx < this.numberOfUAEmitterSystems; idx++) + { + var anX = new dis.AcousticEmitterSystemData(); + anX.initFromBinary(inputStream); + this.emitterSystems.push(anX); + } + + }; + + dis.UaPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeByte(this.stateChangeIndicator); + outputStream.writeByte(this.pad); + outputStream.writeUShort(this.passiveParameterIndex); + outputStream.writeUByte(this.propulsionPlantConfiguration); + outputStream.writeUByte(this.numberOfShafts); + outputStream.writeUByte(this.numberOfAPAs); + outputStream.writeUByte(this.numberOfUAEmitterSystems); + for(var idx = 0; idx < this.shaftRPMs.length; idx++) + { + shaftRPMs[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.apaData.length; idx++) + { + apaData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.emitterSystems.length; idx++) + { + emitterSystems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.UaPdu = dis.UaPdu; + +// End of UaPdu class + +/** + * Wrapper for an unsigned 32 bit integer + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UnsignedIntegerWrapper = function() +{ + /** name can't be too accurate or the generated source code will have reserved word problems */ + this.wrapper = 0; + + dis.UnsignedIntegerWrapper.prototype.initFromBinary = function(inputStream) + { + this.wrapper = inputStream.readUInt(); + }; + + dis.UnsignedIntegerWrapper.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.wrapper); + }; +}; // end of class + + // node.js module support +exports.UnsignedIntegerWrapper = dis.UnsignedIntegerWrapper; + +// End of UnsignedIntegerWrapper class + +/** + * Section 5.2.32. Variable Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VariableDatum = function() +{ + /** ID of the variable datum */ + this.variableDatumID = 0; + + /** length of the variable datums, in bits. Note that this is not programmatically tied to the size of the variableData. The variable data field may be 64 bits long but only 16 bits of it could actually be used. */ + this.variableDatumLength = 0; + + /** data can be any length, but must increase in 8 byte quanta. This requires some postprocessing patches. Note that setting the data allocates a new internal array to account for the possibly increased size. The default initial size is 64 bits. */ + this.variableData = new Array(); + + dis.VariableDatum.prototype.initFromBinary = function(inputStream) + { + this.variableDatumID = inputStream.readUInt(); + this.variableDatumLength = inputStream.readUInt(); + for(var idx = 0; idx < this.variableDatumLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.variableData.push(anX); + } + + }; + + dis.VariableDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.variableDatumID); + outputStream.writeUInt(this.variableDatumLength); + for(var idx = 0; idx < this.variableData.length; idx++) + { + variableData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.VariableDatum = dis.VariableDatum; + +// End of VariableDatum class + +/** + * Section 5.3.34. Three double precision floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Double = function() +{ + /** X value */ + this.x = 0; + + /** Y value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Double.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat64(); + this.y = inputStream.readFloat64(); + this.z = inputStream.readFloat64(); + }; + + dis.Vector3Double.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat64(this.x); + outputStream.writeFloat64(this.y); + outputStream.writeFloat64(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Double = dis.Vector3Double; + +// End of Vector3Double class + +/** + * Section 5.2.33. Three floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Float = function() +{ + /** X value */ + this.x = 0; + + /** y Value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Float.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.Vector3Float.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Float = dis.Vector3Float; + +// End of Vector3Float class + +/** + * Data about a vectoring nozzle system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VectoringNozzleSystemData = function() +{ + /** horizontal deflection angle */ + this.horizontalDeflectionAngle = 0; + + /** vertical deflection angle */ + this.verticalDeflectionAngle = 0; + + dis.VectoringNozzleSystemData.prototype.initFromBinary = function(inputStream) + { + this.horizontalDeflectionAngle = inputStream.readFloat32(); + this.verticalDeflectionAngle = inputStream.readFloat32(); + }; + + dis.VectoringNozzleSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.horizontalDeflectionAngle); + outputStream.writeFloat32(this.verticalDeflectionAngle); + }; +}; // end of class + + // node.js module support +exports.VectoringNozzleSystemData = dis.VectoringNozzleSystemData; + +// End of VectoringNozzleSystemData class + +/** + * Section 5.3.4. abstract superclass for fire and detonation pdus that have shared information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.WarfareFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + dis.WarfareFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + }; + + dis.WarfareFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.WarfareFamilyPdu = dis.WarfareFamilyPdu; + +// End of WarfareFamilyPdu class + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/main.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/main.js new file mode 100644 index 0000000000000000000000000000000000000000..bc28a3a516362a300ec801a57d1681dee862884d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/main.js @@ -0,0 +1,251 @@ + /** This works if you're running client and server on one host. To + * have it work with a remote server, replace localhost with the IP + * or name of the server. + */ + + + var WEBSOCKET_URL="ws://track.movesinstitute.org:80"; + var websocket; + var timerID = 0; + /** A likely map location */ + var montereyLocation = {'latitude':36.595, 'longitude':-121.877}; + var allDisEntities = new Object(); + var pduFactory = new dis.PduFactory(); + var espdu = new dis.EntityStatePdu(); + + var rifleMunition = new dis.EntityType(); + var damageHits = 0; + + + espdu.entityID.entity = Math.round(Math.random() * 64000); + + /** + * Called when the user clicks the "submit" button. Starts a task + * to retrieve the field values, and periodically send ESPDUs based + * on this. + * + * @param {type} form + * @returns {undefined} + */ + function constructiveSend(form) + { + // On a second button press, kill the old send timer and + // start a new one farther down, so we don't have two + // timers sending + if(timerID != 0) + { + console.log("timerID:", timerID) + clearInterval(timerID); + console.log("Killed old periodic send task") + } + + // Fill out entity type info + espdu.entityType.entityKind = parseInt(document.getElementById("entitykind").value); + espdu.entityType.domain = parseInt(document.getElementById("domain").value); + espdu.entityType.country = parseInt(document.getElementById("country").value); + espdu.entityType.category = parseInt(document.getElementById("category").value); + espdu.entityType.subcategory = parseInt(document.getElementById("subcategory").value); + espdu.entityType.specific = parseInt(document.getElementById("specific").value); + espdu.entityType.extra = parseInt(document.getElementById("extra").value); + + // Fill out entity ID + espdu.entityID.site = parseInt(document.getElementById("site").value); + espdu.entityID.application = parseInt(document.getElementById("application").value); + espdu.entityID.entity = Math.round(Math.random() * 65000); + + // Marking + var convert = new dis.StringConversion(); + + espdu.marking.setMarking(document.getElementById("marking").value); + + // Position + var lat = parseFloat(document.getElementById("latitude").value); + var lon = parseFloat(document.getElementById("longitude").value); + var alt = parseFloat(document.getElementById("altitude").value); + + // Convert lat/lon/alt to DIS coordinates + var conversion = new dis.CoordinateConversion(); + latLonAlt = {}; + latLonAlt.lat = lat; + latLonAlt.lon = lon; + latLonAlt.alt = alt; + console.log("Geodetic location:", latLonAlt); + + var disCoordinates = conversion.getXYZfromLatLonAltDegrees(latLonAlt); + espdu.entityLocation.x = disCoordinates.x; + espdu.entityLocation.y = disCoordinates.y; + espdu.entityLocation.z = disCoordinates.z; + console.log("Location:", disCoordinates); + + // How often to send + var frequency = parseInt(document.getElementById("sendfrequency").value); + + // start a repeating task to send it + timerID = setInterval(sendPdu, frequency); + } + + /** + * Called by the timer task. Marshal and send a PDU + * + * @returns {undefined} + */ + function sendPdu() + { + var dataBuffer = new ArrayBuffer(1000); // typically 144 bytes, make it bigger for safety + var outputStream = new dis.OutputStream(dataBuffer); + espdu.encodeToBinary(outputStream); + + var trimmedData = outputStream.toByteArray(); + websocket.send(trimmedData); + console.log("Sent pdu ", espdu); + + } + + /** + * Initialize websocket + * + * @returns {undefined} + */ + function initialize() + { + + websocket = new WebSocket(WEBSOCKET_URL); + + // Set the format we want to use to receive binary messages + websocket.binaryType = 'arraybuffer'; + + // Attach functions to the the web socket for various events + websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; + websocket.onclose = function(evt){console.log("websocket close", evt);}; + websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + // We don't really need to receive anything, just blindly send + websocket.onmessage = function(evt) + { + var aPdu = pduFactory.createPdu(evt.data); + //console.log("PDU:", aPdu); + switch(aPdu.pduType) + { + case 1: + entityStatePduHandler(aPdu); + break; + + case 2: + console.log("Fire PDU:", aPdu); + firePduHandler(aPdu); + break; + + case 3: + console.log("Detonation PDU"); + detonationPduHandler(aPdu); + break; + + default: + break; + } + + } + + } + + /** + * Call this function to process an entity state pdu + * + * @param {EntityStatePdu} espdu + * @returns {void} + */ + function entityStatePduHandler(espdu) + { + if(espdu.pduType != 1) + { + console.log("Sent a non-espdu PDU to entityStatePduHandler"); + return; + } + + // Process an entity state PDU here + } + + + /** + * Call this function to process a FirePdu + * + * @param {FirePdu} firePdu + * @returns {void} + */ + function firePduHandler(firePdu) + { + if(firePdu.pduType != 2) + { + console.log("You sent a PDU that is not a fire PDU to firePduHandler"); + return; + } + + // Process PDU here + } + + /** + * Call this function to process a detonation pdu + * + * @param {DetonationPdu} detonationPdu + * @returns {void} + */ + function detonationPduHandler(detonationPdu) + { + if(detonationPdu.pduType != 3) + { + console.log("You sent a PDU that is not a detonation pdu to detonationPduHandler"); + return; + } + + // Handle the detonation PDU here + + } + + /** + * Write code to assess damage to our entity here. Assume + * that we are killed by two or more 5.56 rifle rounds that + * hit us. We receive the detonation PDU, which contains the + * target ID and the munition. if 1) we're the target, and + * 2) the munition is a rifle round, and (3) the impact + * is in the general area, assume we've been shot. You can + * make use of the entityIDsEqual() and munitionsEqual() + * functions. + * + * @param {type} detonationPdu + * @returns {undefined} + */ + function assessDamageToOurEntities(detonationPdu) + { + console.log("Assessing damage for detonation:", detonationPdu); + } + + function entityIDsEqual(eid1, eid2) + { + if(eid1.site === eid2.site && + eid1.application === eid2.application && + eid1.entity === eid2.entity) + { + return true; + } + + return false; + } + + + function munitionsEqual(firstMunition, secondMunition) + { + if(firstMunition.domain === secondMunition.domain && + firstMunition.entityKind === secondMunition.entityKind && + firstMunition.country === secondMunition.country && + firstMunition.category === secondMunition.category && + firstMunition.subcategory === secondMunition.subcategory && + firstMunition.specific === secondMunition.specific && + firstMunition.extra === secondMunition.extra) + { + return true; + } + + return false; + } + + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/multicastRepeater.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/multicastRepeater.js new file mode 100644 index 0000000000000000000000000000000000000000..2fca44cbb00383e610af4c4dbc56730d0276538f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/multicastRepeater.js @@ -0,0 +1,32 @@ +//listen to muticast +//Multicast Client receiving sent messages +var PORT = 3000; +var MCAST_ADDR = "239.1.2.3"; //same mcast address as Server +var HOST = '172.20.159.255'; //this is your own IP +var dgram = require('dgram'); +var client = dgram.createSocket('udp4'); + +//set up WebSocket repeater +const WebSocket = require('ws'); + +const websocket = new WebSocket('ws://track.movesinstitute.org:80'); + +websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; +websocket.onclose = function(evt){console.log("websocket close", evt);}; +websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + +client.on('listening', function () { + var address = client.address(); + console.log('UDP Client listening on ' + address.address + ":" + address.port); + client.setBroadcast(true) + client.setMulticastTTL(128); + client.addMembership(MCAST_ADDR); +}); + +client.on('message', function (message, remote) { + console.log('MCast Msg: From: ' + remote.address + ':' + remote.port +' - ' + message); + websocket.send(message); +}); + +client.bind(PORT, HOST); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..6cf4a7ad0b7c6317691d092c261498868ab22b53 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "node" +script: npm run travis +cache: + yarn: true diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9c91fb26803ab91013ece7c825691b3c29d3abb6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Samuel Reed <samuel.trace.reed@gmail.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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/coverage.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/coverage.json new file mode 100644 index 0000000000000000000000000000000000000000..5b4a358483e011ff99119eccd56cf4fd48f2e56a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/coverage.json @@ -0,0 +1 @@ +{"/Users/samuelreed/git/forks/async-throttle/index.js":{"path":"/Users/samuelreed/git/forks/async-throttle/index.js","s":{"1":1,"2":7,"3":1,"4":6,"5":6,"6":6,"7":6,"8":6,"9":6,"10":1,"11":1,"12":3,"13":13,"14":13,"15":13,"16":1,"17":19,"18":1,"19":45,"20":6,"21":39,"22":13,"23":13,"24":13,"25":13,"26":39,"27":18,"28":6,"29":6,"30":1,"31":6,"32":6,"33":6,"34":1,"35":13,"36":13,"37":1},"b":{"1":[1,6],"2":[6,5],"3":[6,5],"4":[6,39],"5":[13,26],"6":[18,21],"7":[6,0]},"f":{"1":7,"2":3,"3":13,"4":19,"5":45,"6":6,"7":13},"fnMap":{"1":{"name":"Queue","line":3,"loc":{"start":{"line":3,"column":0},"end":{"line":3,"column":24}}},"2":{"name":"(anonymous_2)","line":22,"loc":{"start":{"line":22,"column":24},"end":{"line":22,"column":41}}},"3":{"name":"(anonymous_3)","line":23,"loc":{"start":{"line":23,"column":28},"end":{"line":23,"column":39}}},"4":{"name":"(anonymous_4)","line":31,"loc":{"start":{"line":31,"column":7},"end":{"line":31,"column":18}}},"5":{"name":"(anonymous_5)","line":36,"loc":{"start":{"line":36,"column":23},"end":{"line":36,"column":34}}},"6":{"name":"(anonymous_6)","line":55,"loc":{"start":{"line":55,"column":25},"end":{"line":55,"column":38}}},"7":{"name":"done","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":16}}}},"statementMap":{"1":{"start":{"line":3,"column":0},"end":{"line":14,"column":1}},"2":{"start":{"line":4,"column":2},"end":{"line":6,"column":3}},"3":{"start":{"line":5,"column":4},"end":{"line":5,"column":30}},"4":{"start":{"line":8,"column":2},"end":{"line":8,"column":26}},"5":{"start":{"line":9,"column":2},"end":{"line":9,"column":53}},"6":{"start":{"line":10,"column":2},"end":{"line":10,"column":19}},"7":{"start":{"line":11,"column":2},"end":{"line":11,"column":17}},"8":{"start":{"line":12,"column":2},"end":{"line":12,"column":16}},"9":{"start":{"line":13,"column":2},"end":{"line":13,"column":31}},"10":{"start":{"line":16,"column":0},"end":{"line":20,"column":2}},"11":{"start":{"line":22,"column":0},"end":{"line":28,"column":3}},"12":{"start":{"line":23,"column":2},"end":{"line":27,"column":4}},"13":{"start":{"line":24,"column":4},"end":{"line":24,"column":75}},"14":{"start":{"line":25,"column":4},"end":{"line":25,"column":16}},"15":{"start":{"line":26,"column":4},"end":{"line":26,"column":24}},"16":{"start":{"line":30,"column":0},"end":{"line":34,"column":3}},"17":{"start":{"line":32,"column":4},"end":{"line":32,"column":43}},"18":{"start":{"line":36,"column":0},"end":{"line":53,"column":2}},"19":{"start":{"line":37,"column":2},"end":{"line":39,"column":3}},"20":{"start":{"line":38,"column":4},"end":{"line":38,"column":11}},"21":{"start":{"line":40,"column":2},"end":{"line":45,"column":3}},"22":{"start":{"line":41,"column":4},"end":{"line":41,"column":32}},"23":{"start":{"line":42,"column":4},"end":{"line":42,"column":19}},"24":{"start":{"line":43,"column":4},"end":{"line":43,"column":20}},"25":{"start":{"line":44,"column":4},"end":{"line":44,"column":16}},"26":{"start":{"line":47,"column":2},"end":{"line":52,"column":3}},"27":{"start":{"line":48,"column":4},"end":{"line":51,"column":5}},"28":{"start":{"line":49,"column":6},"end":{"line":49,"column":30}},"29":{"start":{"line":50,"column":6},"end":{"line":50,"column":27}},"30":{"start":{"line":55,"column":0},"end":{"line":60,"column":2}},"31":{"start":{"line":56,"column":2},"end":{"line":59,"column":3}},"32":{"start":{"line":57,"column":4},"end":{"line":57,"column":22}},"33":{"start":{"line":58,"column":4},"end":{"line":58,"column":16}},"34":{"start":{"line":62,"column":0},"end":{"line":65,"column":1}},"35":{"start":{"line":63,"column":2},"end":{"line":63,"column":17}},"36":{"start":{"line":64,"column":2},"end":{"line":64,"column":14}},"37":{"start":{"line":67,"column":0},"end":{"line":67,"column":23}}},"branchMap":{"1":{"line":4,"type":"if","locations":[{"start":{"line":4,"column":2},"end":{"line":4,"column":2}},{"start":{"line":4,"column":2},"end":{"line":4,"column":2}}]},"2":{"line":8,"type":"binary-expr","locations":[{"start":{"line":8,"column":12},"end":{"line":8,"column":19}},{"start":{"line":8,"column":23},"end":{"line":8,"column":25}}]},"3":{"line":9,"type":"binary-expr","locations":[{"start":{"line":9,"column":21},"end":{"line":9,"column":40}},{"start":{"line":9,"column":44},"end":{"line":9,"column":52}}]},"4":{"line":37,"type":"if","locations":[{"start":{"line":37,"column":2},"end":{"line":37,"column":2}},{"start":{"line":37,"column":2},"end":{"line":37,"column":2}}]},"5":{"line":40,"type":"if","locations":[{"start":{"line":40,"column":2},"end":{"line":40,"column":2}},{"start":{"line":40,"column":2},"end":{"line":40,"column":2}}]},"6":{"line":47,"type":"if","locations":[{"start":{"line":47,"column":2},"end":{"line":47,"column":2}},{"start":{"line":47,"column":2},"end":{"line":47,"column":2}}]},"7":{"line":56,"type":"if","locations":[{"start":{"line":56,"column":2},"end":{"line":56,"column":2}},{"start":{"line":56,"column":2},"end":{"line":56,"column":2}}]}}}} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html new file mode 100644 index 0000000000000000000000000000000000000000..198882b4b1185be9e2062cc932e325dcad1e5df7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html @@ -0,0 +1,73 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for async-throttle/</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="../prettify.css"> + <link rel="stylesheet" href="../base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(../sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">async-throttle/</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"><a href="../index.html">All files</a> » async-throttle/</div> +</div> +<div class="body"> +<div class="coverage-summary"> +<table> +<thead> +<tr> + <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> + <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> + <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> + <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> + <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> + <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> + <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> +</tr> +</thead> +<tbody><tr> + <td class="file high" data-value="index.js"><a href="index.js.html">index.js</a></td> + <td data-value="100" class="pic high"><span class="cover-fill cover-full" style="width: 100px;"></span><span class="cover-empty" style="width:0px;"></span></td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + <td data-value="92.86" class="pct high">92.86%</td> + <td data-value="14" class="abs high">(13 / 14)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="7" class="abs high">(7 / 7)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + </tr> + +</tbody> +</table> +</div> +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="../prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="../sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html new file mode 100644 index 0000000000000000000000000000000000000000..adc030fda975915569d2aa614db5d107dfa3aa06 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html @@ -0,0 +1,246 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for async-throttle/index.js</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="../prettify.css"> + <link rel="stylesheet" href="../base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(../sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">async-throttle/index.js</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"><a href="../index.html">All files</a> » <a href="index.html">async-throttle/</a> » index.js</div> +</div> +<div class="body"> +<pre><table class="coverage"> +<tr><td class="line-count">1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68</td><td class="line-coverage"><span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">7</span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">3</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">19</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">45</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">39</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">39</span> +<span class="cline-any cline-yes">18</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + <span class="missing-if-branch" title="else path not taken" >E</span>if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; + </pre></td></tr> +</table></pre> + +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="../prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="../sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/base.css b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/base.css new file mode 100644 index 0000000000000000000000000000000000000000..a6a2f3284d0221eee83373df7f9ba792601efe51 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/base.css @@ -0,0 +1,182 @@ +body, html { + margin:0; padding: 0; +} +body { + font-family: Helvetica Neue, Helvetica,Arial; + font-size: 10pt; +} +div.header, div.footer { + background: #eee; + padding: 1em; +} +div.header { + z-index: 100; + position: fixed; + top: 0; + border-bottom: 1px solid #666; + width: 100%; +} +div.footer { + border-top: 1px solid #666; +} +div.body { + margin-top: 10em; +} +div.meta { + font-size: 90%; + text-align: center; +} +h1, h2, h3 { + font-weight: normal; +} +h1 { + font-size: 12pt; +} +h2 { + font-size: 10pt; +} +pre { + font-family: Consolas, Menlo, Monaco, monospace; + margin: 0; + padding: 0; + line-height: 1.3; + font-size: 14px; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} + +div.path { font-size: 110%; } +div.path a:link, div.path a:visited { color: #000; } +table.coverage { border-collapse: collapse; margin:0; padding: 0 } + +table.coverage td { + margin: 0; + padding: 0; + color: #111; + vertical-align: top; +} +table.coverage td.line-count { + width: 50px; + text-align: right; + padding-right: 5px; +} +table.coverage td.line-coverage { + color: #777 !important; + text-align: right; + border-left: 1px solid #666; + border-right: 1px solid #666; +} + +table.coverage td.text { +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 40px; +} +table.coverage td span.cline-neutral { + background: #eee; +} +table.coverage td span.cline-yes { + background: #b5d592; + color: #999; +} +table.coverage td span.cline-no { + background: #fc8c84; +} + +.cstat-yes { color: #111; } +.cstat-no { background: #fc8c84; color: #111; } +.fstat-no { background: #ffc520; color: #111 !important; } +.cbranch-no { background: yellow !important; color: #111; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +.missing-if-branch { + display: inline-block; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: black; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} + +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} + +.entity, .metric { font-weight: bold; } +.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } +.metric small { font-size: 80%; font-weight: normal; color: #666; } + +div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } +div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } +div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } +div.coverage-summary th.file { border-right: none !important; } +div.coverage-summary th.pic { border-left: none !important; text-align: right; } +div.coverage-summary th.pct { border-right: none !important; } +div.coverage-summary th.abs { border-left: none !important; text-align: right; } +div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } +div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } +div.coverage-summary td.file { border-left: 1px solid #666; white-space: nowrap; } +div.coverage-summary td.pic { min-width: 120px !important; } +div.coverage-summary a:link { text-decoration: none; color: #000; } +div.coverage-summary a:visited { text-decoration: none; color: #777; } +div.coverage-summary a:hover { text-decoration: underline; } +div.coverage-summary tfoot td { border-top: 1px solid #666; } + +div.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +div.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +div.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} + +.high { background: #b5d592 !important; } +.medium { background: #ffe87c !important; } +.low { background: #fc8c84 !important; } + +span.cover-fill, span.cover-empty { + display:inline-block; + border:1px solid #444; + background: white; + height: 12px; +} +span.cover-fill { + background: #ccc; + border-right: 1px solid #444; +} +span.cover-empty { + background: white; + border-left: none; +} +span.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/index.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/index.html new file mode 100644 index 0000000000000000000000000000000000000000..782a1cff1190b0c243a453b25316d42a8e0cb63b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/index.html @@ -0,0 +1,73 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for All files</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="prettify.css"> + <link rel="stylesheet" href="base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">All files</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"></div> +</div> +<div class="body"> +<div class="coverage-summary"> +<table> +<thead> +<tr> + <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> + <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> + <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> + <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> + <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> + <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> + <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> +</tr> +</thead> +<tbody><tr> + <td class="file high" data-value="async-throttle/"><a href="async-throttle/index.html">async-throttle/</a></td> + <td data-value="100" class="pic high"><span class="cover-fill cover-full" style="width: 100px;"></span><span class="cover-empty" style="width:0px;"></span></td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + <td data-value="92.86" class="pct high">92.86%</td> + <td data-value="14" class="abs high">(13 / 14)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="7" class="abs high">(7 / 7)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + </tr> + +</tbody> +</table> +</div> +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css new file mode 100644 index 0000000000000000000000000000000000000000..b317a7cda31a440fbd47540297ee3c68d51f343e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js new file mode 100644 index 0000000000000000000000000000000000000000..ef51e03866898f709d2bed6f55ed10bfb9840e6f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V<U;++V){var ae=Z[V];if(ae.ignoreCase){ac=true}else{if(/[a-z]/i.test(ae.source.replace(/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi,""))){S=true;ac=false;break}}}var Y={b:8,t:9,n:10,v:11,f:12,r:13};function ab(ah){var ag=ah.charCodeAt(0);if(ag!==92){return ag}var af=ah.charAt(1);ag=Y[af];if(ag){return ag}else{if("0"<=af&&af<="7"){return parseInt(ah.substring(1),8)}else{if(af==="u"||af==="x"){return parseInt(ah.substring(2),16)}else{return ah.charCodeAt(1)}}}}function T(af){if(af<32){return(af<16?"\\x0":"\\x")+af.toString(16)}var ag=String.fromCharCode(af);if(ag==="\\"||ag==="-"||ag==="["||ag==="]"){ag="\\"+ag}return ag}function X(am){var aq=am.substring(1,am.length-1).match(new RegExp("\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]","g"));var ak=[];var af=[];var ao=aq[0]==="^";for(var ar=ao?1:0,aj=aq.length;ar<aj;++ar){var ah=aq[ar];if(/\\[bdsw]/i.test(ah)){ak.push(ah)}else{var ag=ab(ah);var al;if(ar+2<aj&&"-"===aq[ar+1]){al=ab(aq[ar+2]);ar+=2}else{al=ag}af.push([ag,al]);if(!(al<65||ag>122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;ar<af.length;++ar){var at=af[ar];if(at[0]<=ap[1]+1){ap[1]=Math.max(ap[1],at[1])}else{ai.push(ap=at)}}var an=["["];if(ao){an.push("^")}an.push.apply(an,ak);for(var ar=0;ar<ai.length;++ar){var at=ai[ar];an.push(T(at[0]));if(at[1]>at[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak<ah;++ak){var ag=aj[ak];if(ag==="("){++am}else{if("\\"===ag.charAt(0)){var af=+ag.substring(1);if(af&&af<=am){an[af]=-1}}}}for(var ak=1;ak<an.length;++ak){if(-1===an[ak]){an[ak]=++ad}}for(var ak=0,am=0;ak<ah;++ak){var ag=aj[ak];if(ag==="("){++am;if(an[am]===undefined){aj[ak]="(?:"}}else{if("\\"===ag.charAt(0)){var af=+ag.substring(1);if(af&&af<=am){aj[ak]="\\"+an[am]}}}}for(var ak=0,am=0;ak<ah;++ak){if("^"===aj[ak]&&"^"!==aj[ak+1]){aj[ak]=""}}if(al.ignoreCase&&S){for(var ak=0;ak<ah;++ak){var ag=aj[ak];var ai=ag.charAt(0);if(ag.length>=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V<U;++V){var ae=Z[V];if(ae.global||ae.multiline){throw new Error(""+ae)}aa.push("(?:"+W(ae)+")")}return new RegExp(aa.join("|"),ac?"gi":"g")}function a(V){var U=/(?:^|\s)nocode(?:\s|$)/;var X=[];var T=0;var Z=[];var W=0;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=document.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Y=S&&"pre"===S.substring(0,3);function aa(ab){switch(ab.nodeType){case 1:if(U.test(ab.className)){return}for(var ae=ab.firstChild;ae;ae=ae.nextSibling){aa(ae)}var ad=ab.nodeName;if("BR"===ad||"LI"===ad){X[W]="\n";Z[W<<1]=T++;Z[(W++<<1)|1]=ab}break;case 3:case 4:var ac=ab.nodeValue;if(ac.length){if(!Y){ac=ac.replace(/[ \t\r\n]+/g," ")}else{ac=ac.replace(/\r\n?/g,"\n")}X[W]=ac;Z[W<<1]=T;T+=ac.length;Z[(W++<<1)|1]=ab}break}}aa(V);return{sourceCode:X.join("").replace(/\n$/,""),spans:Z}}function B(S,U,W,T){if(!U){return}var V={sourceCode:U,basePos:S};W(V);T.push.apply(T,V.decorations)}var v=/\S/;function o(S){var V=undefined;for(var U=S.firstChild;U;U=U.nextSibling){var T=U.nodeType;V=(T===1)?(V?S:U):(T===3)?(v.test(U.nodeValue)?S:V):V}return V===S?undefined:V}function g(U,T){var S={};var V;(function(){var ad=U.concat(T);var ah=[];var ag={};for(var ab=0,Z=ad.length;ab<Z;++ab){var Y=ad[ab];var ac=Y[3];if(ac){for(var ae=ac.length;--ae>=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae<aq;++ae){var ag=an[ae];var ap=aj[ag];var ai=void 0;var am;if(typeof ap==="string"){am=false}else{var aa=S[ag.charAt(0)];if(aa){ai=ag.match(aa[1]);ap=aa[0]}else{for(var ao=0;ao<X;++ao){aa=T[ao];ai=ag.match(aa[1]);if(ai){ap=aa[0];break}}if(!ai){ap=F}}am=ap.length>=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y<W.length;++Y){ae(W[Y])}if(ag===(ag|0)){W[0].setAttribute("value",ag)}var aa=ac.createElement("OL");aa.className="linenums";var X=Math.max(0,((ag-1))|0)||0;for(var Y=0,T=W.length;Y<T;++Y){af=W[Y];af.className="L"+((Y+X)%10);if(!af.firstChild){af.appendChild(ac.createTextNode("\xA0"))}aa.appendChild(af)}V.appendChild(aa)}function D(ac){var aj=/\bMSIE\b/.test(navigator.userAgent);var am=/\n/g;var al=ac.sourceCode;var an=al.length;var V=0;var aa=ac.spans;var T=aa.length;var ah=0;var X=ac.decorations;var Y=X.length;var Z=0;X[Y]=an;var ar,aq;for(aq=ar=0;aq<Y;){if(X[aq]!==X[aq+2]){X[ar++]=X[aq++];X[ar++]=X[aq++]}else{aq+=2}}Y=ar;for(aq=ar=0;aq<Y;){var at=X[aq];var ab=X[aq+1];var W=aq+2;while(W+2<=Y&&X[W+1]===ab){W+=2}X[ar++]=at;X[ar++]=ab;aq=W}Y=X.length=ar;var ae=null;while(ah<T){var af=aa[ah];var S=aa[ah+2]||an;var ag=X[Z];var ap=X[Z+2]||an;var W=Math.min(S,ap);var ak=aa[ah+1];var U;if(ak.nodeType!==1&&(U=al.substring(V,W))){if(aj){U=U.replace(am,"\r")}ak.nodeValue=U;var ai=ak.ownerDocument;var ao=ai.createElement("SPAN");ao.className=X[Z+1];var ad=ak.parentNode;ad.replaceChild(ao,ak);ao.appendChild(ak);if(V<S){aa[ah+1]=ak=ai.createTextNode(al.substring(W,S));ad.insertBefore(ak,ao.nextSibling)}}V=W;if(V>=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*</.test(S)?"default-markup":"default-code"}return t[T]}c(K,["default-code"]);c(g([],[[F,/^[^<?]+/],[E,/^<!\w[^>]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa<ac.length;++aa){for(var Z=0,V=ac[aa].length;Z<V;++Z){T.push(ac[aa][Z])}}ac=null;var W=Date;if(!W.now){W={now:function(){return +(new Date)}}}var X=0;var S;var ab=/\blang(?:uage)?-([\w.]+)(?!\S)/;var ae=/\bprettyprint\b/;function U(){var ag=(window.PR_SHOULD_USE_CONTINUATION?W.now()+250:Infinity);for(;X<T.length&&W.now()<ag;X++){var aj=T[X];var ai=aj.className;if(ai.indexOf("prettyprint")>=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X<T.length){setTimeout(U,250)}else{if(ad){ad()}}}U()}window.prettyPrintOne=y;window.prettyPrint=b;window.PR={createSimpleLexer:g,registerLangHandler:c,sourceDecorator:i,PR_ATTRIB_NAME:P,PR_ATTRIB_VALUE:n,PR_COMMENT:j,PR_DECLARATION:E,PR_KEYWORD:z,PR_LITERAL:G,PR_NOCODE:N,PR_PLAIN:F,PR_PUNCTUATION:L,PR_SOURCE:J,PR_STRING:C,PR_TAG:m,PR_TYPE:O}})();PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_DECLARATION,/^<!\w[^>]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^<script\b[^>]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:<!--|-->)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js new file mode 100644 index 0000000000000000000000000000000000000000..6afb736c39fb15da83c56b083ab88b505c247a38 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js @@ -0,0 +1,156 @@ +var addSorting = (function () { + "use strict"; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { return document.querySelector('.coverage-summary table'); } + // returns the thead element of the summary table + function getTableHeader() { return getTable().querySelector('thead tr'); } + // returns the tbody element of the summary table + function getTableBody() { return getTable().querySelector('tbody'); } + // returns the th element for nth column + function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = colNode.innerHTML + '<span class="sorter"></span>'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov.info b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov.info new file mode 100644 index 0000000000000000000000000000000000000000..fbf36aab035770e2b116084456e1367e9506b090 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/coverage/lcov.info @@ -0,0 +1,74 @@ +TN: +SF:/Users/samuelreed/git/forks/async-throttle/index.js +FN:3,Queue +FN:22,(anonymous_2) +FN:23,(anonymous_3) +FN:31,(anonymous_4) +FN:36,(anonymous_5) +FN:55,(anonymous_6) +FN:62,done +FNF:7 +FNH:7 +FNDA:7,Queue +FNDA:3,(anonymous_2) +FNDA:13,(anonymous_3) +FNDA:19,(anonymous_4) +FNDA:45,(anonymous_5) +FNDA:6,(anonymous_6) +FNDA:13,done +DA:3,1 +DA:4,7 +DA:5,1 +DA:8,6 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:16,1 +DA:22,1 +DA:23,3 +DA:24,13 +DA:25,13 +DA:26,13 +DA:30,1 +DA:32,19 +DA:36,1 +DA:37,45 +DA:38,6 +DA:40,39 +DA:41,13 +DA:42,13 +DA:43,13 +DA:44,13 +DA:47,39 +DA:48,18 +DA:49,6 +DA:50,6 +DA:55,1 +DA:56,6 +DA:57,6 +DA:58,6 +DA:62,1 +DA:63,13 +DA:64,13 +DA:67,1 +LF:37 +LH:37 +BRDA:4,1,0,1 +BRDA:4,1,1,6 +BRDA:8,2,0,6 +BRDA:8,2,1,5 +BRDA:9,3,0,6 +BRDA:9,3,1,5 +BRDA:37,4,0,6 +BRDA:37,4,1,39 +BRDA:40,5,0,13 +BRDA:40,5,1,26 +BRDA:47,6,0,18 +BRDA:47,6,1,21 +BRDA:56,7,0,6 +BRDA:56,7,1,0 +BRF:14 +BRH:13 +end_of_record diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c9bd2f9778213d8adbab4c8a17d13e32aa3fc25b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/index.js @@ -0,0 +1,67 @@ +'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/package.json new file mode 100644 index 0000000000000000000000000000000000000000..86e7eb7066857bee439de93ef6c59538ec606790 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/package.json @@ -0,0 +1,69 @@ +{ + "_from": "async-limiter@~1.0.0", + "_id": "async-limiter@1.0.0", + "_inBundle": false, + "_integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "_location": "/async-limiter", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async-limiter@~1.0.0", + "name": "async-limiter", + "escapedName": "async-limiter", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/ws" + ], + "_resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "_shasum": "78faed8c3d074ab81f22b4e985d79e8738f720f8", + "_spec": "async-limiter@~1.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/ws", + "author": { + "name": "Samuel Reed" + }, + "bugs": { + "url": "https://github.com/strml/async-limiter/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "asynchronous function queue with adjustable concurrency", + "devDependencies": { + "coveralls": "^2.11.2", + "eslint": "^4.6.1", + "eslint-plugin-mocha": "^4.11.0", + "intelli-espower-loader": "^1.0.1", + "istanbul": "^0.3.2", + "mocha": "^3.5.2", + "power-assert": "^1.4.4" + }, + "homepage": "https://github.com/strml/async-limiter#readme", + "keywords": [ + "throttle", + "async", + "limiter", + "asynchronous", + "job", + "task", + "concurrency", + "concurrent" + ], + "license": "MIT", + "name": "async-limiter", + "repository": { + "type": "git", + "url": "git+https://github.com/strml/async-limiter.git" + }, + "scripts": { + "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | coveralls", + "example": "node example", + "lint": "eslint .", + "test": "mocha --R intelli-espower-loader test/", + "travis": "npm run lint && npm run coverage" + }, + "version": "1.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/readme.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..dcf4932f9a8cccba8c30a617efbde48c0f93da80 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/async-limiter/readme.md @@ -0,0 +1,132 @@ +# Async-Limiter + +A module for limiting concurrent asynchronous actions in flight. Forked from [queue](https://github.com/jessetane/queue). + +[](http://www.npmjs.org/async-limiter) +[](https://travis-ci.org/STRML/async-limiter) +[](https://coveralls.io/r/STRML/async-limiter) + +This module exports a class `Limiter` that implements some of the `Array` API. +Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods. + +## Motivation + +Certain functions, like `zlib`, have [undesirable behavior](https://github.com/nodejs/node/issues/8871#issuecomment-250915913) when +run at infinite concurrency. + +In this case, it is actually faster, and takes far less memory, to limit concurrency. + +This module should do the absolute minimum work necessary to queue up functions. PRs are welcome that would +make this module faster or lighter, but new functionality is not desired. + +Style should confirm to nodejs/node style. + +## Example + +``` javascript +var Limiter = require('async-limiter') + +var t = new Limiter({concurrency: 2}); +var results = [] + +// add jobs using the familiar Array API +t.push(function (cb) { + results.push('two') + cb() +}) + +t.push( + function (cb) { + results.push('four') + cb() + }, + function (cb) { + results.push('five') + cb() + } +) + +t.unshift(function (cb) { + results.push('one') + cb() +}) + +t.splice(2, 0, function (cb) { + results.push('three') + cb() +}) + +// Jobs run automatically. If you want a callback when all are done, +// call 'onDone()'. +t.onDone(function () { + console.log('all done:', results) +}) +``` + +## Zlib Example + +```js +const zlib = require('zlib'); +const Limiter = require('async-limiter'); + +const message = {some: "data"}; +const payload = new Buffer(JSON.stringify(message)); + +// Try with different concurrency values to see how this actually +// slows significantly with higher concurrency! +// +// 5: 1398.607ms +// 10: 1375.668ms +// Infinity: 4423.300ms +// +const t = new Limiter({concurrency: 5}); +function deflate(payload, cb) { + t.push(function(done) { + zlib.deflate(payload, function(err, buffer) { + done(); + cb(err, buffer); + }); + }); +} + +console.time('deflate'); +for(let i = 0; i < 30000; ++i) { + deflate(payload, function (err, buffer) {}); +} +q.onDone(function() { + console.timeEnd('deflate'); +}); +``` + +## Install + +`npm install async-limiter` + +## Test + +`npm test` + +## API + +### `var t = new Limiter([opts])` +Constructor. `opts` may contain inital values for: +* `q.concurrency` + +## Instance methods + +### `q.onDone(fn)` +`fn` will be called once and only once, when the queue is empty. + +## Instance methods mixed in from `Array` +Mozilla has docs on how these methods work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). +### `q.push(element1, ..., elementN)` +### `q.unshift(element1, ..., elementN)` +### `q.splice(index , howMany[, element1[, ...[, elementN]]])` + +## Properties +### `q.concurrency` +Max number of jobs the queue should process concurrently, defaults to `Infinity`. + +### `q.length` +Jobs pending + jobs to process (readonly). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.coveralls.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000000000000000000000000000000000000..20a7068581791335487166ddc5001a2ca3a3b060 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.eslintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8a37ae2c2e5a35db74b4607b4c74e0f4fe39a3e4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.npmignore b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..5f60eecc84e219e52554407ad38d04abd1cf2111 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c6090c3b09f2e45d8c0a1dc77ff5f4a81e78a3c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..eadaa189517bbcfb2a6784a48ac8d05d2edafe7c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..658c933d28255e8c716899789e8c0f846e5dc125 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..584da8bf938e639ece3ba2bd4105c215c2b1ff51 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f67be6b317c19952bb506a9e15e797615eea4533 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers) +[](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + +  + +  + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + +  + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + +  + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + +  + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + +<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + +<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/component.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/component.json new file mode 100644 index 0000000000000000000000000000000000000000..9de26410f0d0bba2e48a07f094407d602eb5dd89 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/karma.conf.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..103a82d15bd72b3cdf9ba4108272985f7e0bfdb3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/node.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/node.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc36fe6dbecbfd41530c5a490cc738ec2968653 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e06c2429b209e2cccd09bfc43bdfbf66832e3580 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/package.json @@ -0,0 +1,88 @@ +{ + "_from": "debug@^2.2.0", + "_id": "debug@2.6.9", + "_inBundle": false, + "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "debug@^2.2.0", + "name": "debug", + "escapedName": "debug", + "rawSpec": "^2.2.0", + "saveSpec": null, + "fetchSpec": "^2.2.0" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", + "_spec": "debug@^2.2.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "2.0.0" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "2.6.9" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7106924934501fd4035efe78678281020328acc5 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/debug.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..6a5e3fc94c3ab80e123c3056b6c5dbe056d21658 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e12cf4d58c9f2d6d2d2e656f9cbb0f703cb5fa29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/inspector-log.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000000000000000000000000000000000000..60ea6c04aafd41d0ea3bcd78f58312ecf0eda436 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/node.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..b15109c905a45bcb5db701cf37cf4e19385c3167 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/LICENSE.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/LICENSE.md @@ -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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/README.md new file mode 100644 index 0000000000000000000000000000000000000000..275286391935842285d869d8a18949e04ca20fdf --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/README.md @@ -0,0 +1,16 @@ +# is-typedarray [](http://github.com/badges/stability-badges) + +Detect whether or not an object is a +[Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). + +## Usage + +[](https://nodei.co/npm/is-typedarray/) + +### isTypedArray(array) + +Returns `true` when array is a Typed Array, and `false` when it is not. + +## License + +MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/index.js new file mode 100644 index 0000000000000000000000000000000000000000..58596036cdf15908a729e6547936eef72b2d2e60 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/index.js @@ -0,0 +1,41 @@ +module.exports = isTypedArray +isTypedArray.strict = isStrictTypedArray +isTypedArray.loose = isLooseTypedArray + +var toString = Object.prototype.toString +var names = { + '[object Int8Array]': true + , '[object Int16Array]': true + , '[object Int32Array]': true + , '[object Uint8Array]': true + , '[object Uint8ClampedArray]': true + , '[object Uint16Array]': true + , '[object Uint32Array]': true + , '[object Float32Array]': true + , '[object Float64Array]': true +} + +function isTypedArray(arr) { + return ( + isStrictTypedArray(arr) + || isLooseTypedArray(arr) + ) +} + +function isStrictTypedArray(arr) { + return ( + arr instanceof Int8Array + || arr instanceof Int16Array + || arr instanceof Int32Array + || arr instanceof Uint8Array + || arr instanceof Uint8ClampedArray + || arr instanceof Uint16Array + || arr instanceof Uint32Array + || arr instanceof Float32Array + || arr instanceof Float64Array + ) +} + +function isLooseTypedArray(arr) { + return names[toString.call(arr)] +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d3638d95265bfd714cb0ca7f61bbbf5b567565ba --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/package.json @@ -0,0 +1,59 @@ +{ + "_from": "is-typedarray@^1.0.0", + "_id": "is-typedarray@1.0.0", + "_inBundle": false, + "_integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "_location": "/is-typedarray", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-typedarray@^1.0.0", + "name": "is-typedarray", + "escapedName": "is-typedarray", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/typedarray-to-buffer" + ], + "_resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "_shasum": "e479c80858df0c1b11ddda6940f96011fcda4a9a", + "_spec": "is-typedarray@^1.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/typedarray-to-buffer", + "author": { + "name": "Hugh Kennedy", + "email": "hughskennedy@gmail.com", + "url": "http://hughsk.io/" + }, + "bugs": { + "url": "https://github.com/hughsk/is-typedarray/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Detect whether or not an object is a Typed Array", + "devDependencies": { + "tape": "^2.13.1" + }, + "homepage": "https://github.com/hughsk/is-typedarray", + "keywords": [ + "typed", + "array", + "detect", + "is", + "util" + ], + "license": "MIT", + "main": "index.js", + "name": "is-typedarray", + "repository": { + "type": "git", + "url": "git://github.com/hughsk/is-typedarray.git" + }, + "scripts": { + "test": "node test" + }, + "version": "1.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/test.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/test.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c176fa302aa0c3aacab1287893ee5c1f8b07d6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/is-typedarray/test.js @@ -0,0 +1,34 @@ +var test = require('tape') +var ista = require('./') + +test('strict', function(t) { + t.ok(ista.strict(new Int8Array), 'Int8Array') + t.ok(ista.strict(new Int16Array), 'Int16Array') + t.ok(ista.strict(new Int32Array), 'Int32Array') + t.ok(ista.strict(new Uint8Array), 'Uint8Array') + t.ok(ista.strict(new Uint16Array), 'Uint16Array') + t.ok(ista.strict(new Uint32Array), 'Uint32Array') + t.ok(ista.strict(new Float32Array), 'Float32Array') + t.ok(ista.strict(new Float64Array), 'Float64Array') + + t.ok(!ista.strict(new Array), 'Array') + t.ok(!ista.strict([]), '[]') + + t.end() +}) + +test('loose', function(t) { + t.ok(ista.loose(new Int8Array), 'Int8Array') + t.ok(ista.loose(new Int16Array), 'Int16Array') + t.ok(ista.loose(new Int32Array), 'Int32Array') + t.ok(ista.loose(new Uint8Array), 'Uint8Array') + t.ok(ista.loose(new Uint16Array), 'Uint16Array') + t.ok(ista.loose(new Uint32Array), 'Uint32Array') + t.ok(ista.loose(new Float32Array), 'Float32Array') + t.ok(ista.loose(new Float64Array), 'Float64Array') + + t.ok(!ista.loose(new Array), 'Array') + t.ok(!ista.loose([]), '[]') + + t.end() +}) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6a522b16b3a3bf5e93aa5b8bf485f866ff71c5c2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/license.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..69b61253a38926757b7de1d4df4880fc2105c2c9 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a4e0bc23516ba7d553444e45f90693e05e88916f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/package.json @@ -0,0 +1,69 @@ +{ + "_from": "ms@2.0.0", + "_id": "ms@2.0.0", + "_inBundle": false, + "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.0.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", + "_spec": "ms@2.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/debug", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Tiny milisecond conversion utility", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/readme.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..84a9974cccd81f9296b7d3c77f2b0d2765dfe181 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[](https://travis-ci.org/zeit/ms) +[](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..091cdd1cc9a3c83d66ce6aac072e21a684b72613 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/CHANGELOG.md @@ -0,0 +1,492 @@ +# NAN ChangeLog + +**Version 2.10.0: current Node 9.8.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1** + +### 2.10.0 Mar 16 2018 + + - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950 + - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452 + - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b + - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a + +### 2.9.2 Feb 22 2018 + + - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b + +### 2.9.1 Feb 22 2018 + + - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4 + - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2 + +### 2.9.0 Feb 22 2018 + + - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309 + - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o + - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee + - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4 + - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606 + - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c + - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b + +### 2.8.0 Nov 15 2017 + + - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb + - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900 + - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + +### 2.7.0 Aug 30 2017 + + - Feature: Add `Nan::To<v8::Function>()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b + - Bugfix: Fix ternary in `Nan::MaybeLocal<T>::FromMaybe<S>()`. 79a26f7d362e756a9524e672a82c3d603b542867 + +### 2.6.2 Apr 12 2017 + + - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d + +### 2.6.1 Apr 6 2017 + + - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51 + +### 2.6.0 Apr 6 2017 + + - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5 + +### 2.5.1 Jan 23 2017 + + - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0 + - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112 + - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50 + +### 2.5.0 Dec 21 2016 + + - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178 + - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018 + +### 2.4.0 Jul 10 2016 + + - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649 + - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0 + - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2 + +### 2.3.5 May 31 2016 + + - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909 + +### 2.3.4 May 31 2016 + + - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9 + - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246 + - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc + - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8 + +### 2.3.3 May 4 2016 + + - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8 + +### 2.3.2 Apr 27 2016 + + - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52 + +### 2.3.1 Apr 27 2016 + + - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e + +### 2.3.0 Apr 27 2016 + + - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38 + - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece + +### 2.2.1 Mar 29 2016 + + - Bugfix: Use NewFromUnsigned in ReturnValue<T>::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58 + - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9 + +### 2.2.0 Jan 9 2016 + + - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6 + - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec + - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9 + - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b + +### 2.1.0 Oct 8 2015 + + - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c + - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555 + - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d + - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b + - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537 + - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff + - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f + +### 2.0.9 Sep 8 2015 + + - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 + +### 2.0.8 Aug 28 2015 + + - Work around duplicate linking bug in clang 11902da + +### 2.0.7 Aug 26 2015 + + - Build: Repackage + +### 2.0.6 Aug 26 2015 + + - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 + - Bugfix: Remove unused static std::map instances 525bddc + - Bugfix: Make better use of maybe versions of APIs bfba85b + - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d + +### 2.0.5 Aug 10 2015 + + - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 + - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d + +### 2.0.4 Aug 6 2015 + + - Build: Repackage + +### 2.0.3 Aug 6 2015 + + - Bugfix: Don't use clang++ / g++ syntax extension. 231450e + +### 2.0.2 Aug 6 2015 + + - Build: Repackage + +### 2.0.1 Aug 6 2015 + + - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 + - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 + - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f + - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed + +### 2.0.0 Jul 31 2015 + + - Change: Renamed identifiers with leading underscores b5932b4 + - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 + - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 + - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 + - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 + - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d + - Change: Remove Nan prefix from all names 72d1f67 + - Change: Update Buffer API for new upstream changes d5d3291 + - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a + - Change: Get rid of Handles e6c0daf + - Feature: Support io.js 3 with V8 4.4 + - Feature: Introduce NanPersistent 7fed696 + - Feature: Introduce NanGlobal 4408da1 + - Feature: Added NanTryCatch 10f1ca4 + - Feature: Update for V8 v4.3 4b6404a + - Feature: Introduce NanNewOneByteString c543d32 + - Feature: Introduce namespace Nan 67ed1b1 + - Removal: Remove NanLocker and NanUnlocker dd6e401 + - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 + - Removal: Remove NanReturn* macros d90a25c + - Removal: Remove HasInstance e8f84fe + + +### 1.9.0 Jul 31 2015 + + - Feature: Added `NanFatalException` 81d4a2c + - Feature: Added more error types 4265f06 + - Feature: Added dereference and function call operators to NanCallback c4b2ed0 + - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c + - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 + - Feature: Added NanErrnoException dd87d9e + - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 + - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c + - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew<v8::String, std::string>(std::string) + - Added NanNew<v8::String, std::string&>(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv) + - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv) + - Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv) + - Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value) + - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of + v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local<Value> argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)` + - Added `Local<Function> NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local<Value>[])` + - Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/LICENSE.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..dddd13d5c1ddf8513fbfefe445e482ef2b16cbc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2018 NAN contributors +----------------------------------- + +*NAN contributors listed at <https://github.com/nodejs/nan#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. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4851baab4f1ec82b9032a37beb243d8f3867742 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/README.md @@ -0,0 +1,456 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8 and 9.** + +***Current version: 2.10.0*** + +*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[](https://nodei.co/npm/nan/) [](https://nodei.co/npm/nan/) + +[](http://travis-ci.org/nodejs/nan) +[](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Knowns issues](#issues)** + * **[Governance & Contributing](#governance)** + +<a name="news"></a> + +## News & Updates + +<a name="usage"></a> + +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files: + +``` python +"include_dirs" : [ + "<!(node -e \"require('nan')\")" +] +``` + +This works like a `-I<path-to-NAN>` when compiling your addon. + +<a name="example"></a> + +## Example + +Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. + +Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. + +For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + +Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. + +<a name="api"></a> + +## API + +Additional to the NAN documentation below, please consult: + +* [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding) +* [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide) +* [V8 API Documentation](http://v8docs.nodesource.com/) +* [Node Add-on Documentation](https://nodejs.org/api/addons.html) + +<!-- START API --> + +### JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a> + - <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a> + - <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a> +* **Method declarations** + - <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a> + - <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a> + - <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a> + - <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a> + - <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a> + - <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a> +* Method and template helpers + - <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a> + - <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a> + - <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a> + - <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a> + +### Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> + - <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). + +### Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a> + - <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a> + - <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a> + - <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a> + - <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a> + - <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a> + - <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a> + - <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a> + - <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a> + - <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a> + - <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a> + - <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a> + + +### Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a> + +### Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a> + - <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a> + - <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a> + - <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a> +* **Maybe Helpers** + - <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a> + - <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a> + +### Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> + - <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> + + +### JSON + +The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. + + - <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> + - <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> + +Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. + +### Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a> + - <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a> + - <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a> + - <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a> + - <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a> + - <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a> + - <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a> + - <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a> + + +### Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> + - <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> + - <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> + +### Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a> + +### Asynchronous work helpers + +`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. + + - <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a> + +### Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> + - <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a> + - <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> + - <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> + + +### Object Wrappers + +The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. + + - <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a> + + +### V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a> + + +### Miscellaneous V8 Helpers + + - <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> + - <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> + + +### Miscellaneous Node Helpers + + - <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a> + - <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a> + - <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a> + - <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a> + +<!-- END API --> + + +<a name="tests"></a> + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + +<a name="issues"></a> + +## Known issues + +### Compiling against Node.js 0.12 on OSX + +With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12 +do not compile anymore. The error looks something like: + +``` +⯠CXX(target) Release/obj.target/accessors/cpp/accessors.o +In file included from ../cpp/accessors.cpp:9: +In file included from ../../nan.h:51: +In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: +/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' + return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle( + ~~~~~~~~~~~~~^~~~~~~~~~~~ +``` + +This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make +`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore +this patch cannot be released by either project in an official release. + +For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support +that configuration, you will need to either get an older compiler, or apply a source patch to the version +of V8 headers as a workaround. + +<a name="governance"></a> + +## Governance & Contributing + +NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api) + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +<a id="developers-certificate-of-origin"></a> + +## Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +<a name="collaborators"></a> + +### WG Members / Collaborators + +<table><tbody> +<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr> +<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr> +<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr> +<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr> +<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr> +<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr> +<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr> +<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr> +</tbody></table> + +## Licence & copyright + +Copyright (c) 2018 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/asyncworker.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/asyncworker.md new file mode 100644 index 0000000000000000000000000000000000000000..239de801c1e5a82069ba19f1905babd36150dda5 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/asyncworker.md @@ -0,0 +1,146 @@ +## Asynchronous work helpers + +`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. + + - <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a> + - <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker</code></b></a> + - <a href="#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a> + - <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a> + +<a name="api_nan_async_worker"></a> +### Nan::AsyncWorker + +`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress. + +This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the +correct async context. To be able to identify the async resources created by this class in async-hooks, provide a +`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid +collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation. The `resource_name` needs to stay valid for the lifetime of the worker instance. + +Definition: + +```c++ +class AsyncWorker { + public: + explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker"); + + virtual ~AsyncWorker(); + + virtual void WorkComplete(); + + void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value); + + void SaveToPersistent(const v8::Local<v8::String> &key, + const v8::Local<v8::Value> &value); + + void SaveToPersistent(uint32_t index, + const v8::Local<v8::Value> &value); + + v8::Local<v8::Value> GetFromPersistent(const char *key) const; + + v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const; + + v8::Local<v8::Value> GetFromPersistent(uint32_t index) const; + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy(); + + protected: + Persistent<v8::Object> persistentHandle; + + Callback *callback; + + virtual void HandleOKCallback(); + + virtual void HandleErrorCallback(); + + void SetErrorMessage(const char *msg); + + const char* ErrorMessage(); +}; +``` + +<a name="api_nan_async_progress_worker"></a> +### Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker + +`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. + +Previously the definiton of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `<char>` for compatibility. + +`Nan::AsyncProgressWorkerBase` & `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar. The last event sent before the main thread is woken will be delivered. + +Definition: + +```c++ +template<class T> +class AsyncProgressWorkerBase<T> : public AsyncWorker { + public: + explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...); + + virtual ~AsyncProgressWorkerBase(); + + void WorkProgress(); + + class ExecutionProgress { + public: + void Signal() const; + void Send(const T* data, size_t count) const; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + + virtual void HandleProgressCallback(const T *data, size_t count) = 0; + + virtual void Destroy(); +}; + +typedef AsyncProgressWorkerBase<T> AsyncProgressWorker; +``` + +<a name="api_nan_async_progress_queue_worker"></a> +### Nan::AsyncProgressQueueWorker + +`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. + +`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread. + +Definition: + +```c++ +template<class T> +class AsyncProgressQueueWorker<T> : public AsyncWorker { + public: + explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker"); + + virtual ~AsyncProgressQueueWorker(); + + void WorkProgress(); + + class ExecutionProgress { + public: + void Send(const T* data, size_t count) const; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + + virtual void HandleProgressCallback(const T *data, size_t count) = 0; + + virtual void Destroy(); +}; +``` + +<a name="api_nan_async_queue_worker"></a> +### Nan::AsyncQueueWorker + +`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`. + +Definition: + +```c++ +void AsyncQueueWorker(AsyncWorker *); +``` + +[AsyncResource]: "node_misc.html#api_nan_asyncresource" diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/buffers.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/buffers.md new file mode 100644 index 0000000000000000000000000000000000000000..8d8d25cf75a854d989ef7bc498caa7721913b89a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/buffers.md @@ -0,0 +1,54 @@ +## Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> + - <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> + - <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> + +<a name="api_nan_new_buffer"></a> +### Nan::NewBuffer() + +Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`. + +Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management. +When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`. +You _must not_ free the memory space manually once you have created a `Buffer` in this way. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size) +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size) +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data, + size_t length, + Nan::FreeCallback callback, + void *hint) +``` + + +<a name="api_nan_copy_buffer"></a> +### Nan::CopyBuffer() + +Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`. + +Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size) +``` + + +<a name="api_nan_free_callback"></a> +### Nan::FreeCallback() + +A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer). +The supplied callback will be invoked when the `Buffer` undergoes garbage collection. + +Signature: + +```c++ +typedef void (*FreeCallback)(char *data, void *hint); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/callback.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/callback.md new file mode 100644 index 0000000000000000000000000000000000000000..f7af0bfd9d8281f2eb7e16fc57e787ce54ebeda2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/callback.md @@ -0,0 +1,76 @@ +## Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a> + +<a name="api_nan_callback"></a> +### Nan::Callback + +```c++ +class Callback { + public: + Callback(); + + explicit Callback(const v8::Local<v8::Function> &fn); + + ~Callback(); + + bool operator==(const Callback &other) const; + + bool operator!=(const Callback &other) const; + + v8::Local<v8::Function> operator*() const; + + MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, + v8::Local<v8::Object> target, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + void SetFunction(const v8::Local<v8::Function> &fn); + + v8::Local<v8::Function> GetFunction() const; + + bool IsEmpty() const; + + void Reset(const v8::Local<v8::Function> &fn); + + void Reset(); + + MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target, + int argc, + v8::Local<v8::Value> argv[], + AsyncResource* async_resource) const; + MaybeLocal<v8::Value> Call(int argc, + v8::Local<v8::Value> argv[], + AsyncResource* async_resource) const; + + // Deprecated versions. Use the versions that accept an async_resource instead + // as they run the callback in the correct async context as specified by the + // resource. If you want to call a synchronous JS function (i.e. on a + // non-empty JS stack), you can use Nan::Call instead. + v8::Local<v8::Value> operator()(v8::Local<v8::Object> target, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + v8::Local<v8::Value> operator()(int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + v8::Local<v8::Value> Call(v8::Local<v8::Object> target, + int argc, + v8::Local<v8::Value> argv[]) const; + + v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const; +}; +``` + +Example usage: + +```c++ +v8::Local<v8::Function> function; +Nan::Callback callback(function); +callback.Call(0, 0); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/converters.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/converters.md new file mode 100644 index 0000000000000000000000000000000000000000..d20861b5935b6208b594b91f67cabd27a2bb5558 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/converters.md @@ -0,0 +1,41 @@ +## Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - <a href="#api_nan_to"><b><code>Nan::To()</code></b></a> + +<a name="api_nan_to"></a> +### Nan::To() + +Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly. + +See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types. + +Signatures: + +```c++ +// V8 types +Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val); + +// Native types +Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val); +Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val); +Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val); +Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val); +Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val); +``` + +### Example + +```c++ +v8::Local<v8::Value> val; +Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val); +Nan::Maybe<double> d = Nan::To<double>(val); +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/errors.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/errors.md new file mode 100644 index 0000000000000000000000000000000000000000..b93b3535c7f9e4bbf5077da17f3cf383bb0cf1e6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/errors.md @@ -0,0 +1,226 @@ +## Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a> + - <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a> + - <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a> + - <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a> + - <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a> + - <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a> + - <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a> + - <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a> + - <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a> + - <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a> + - <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a> + - <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a> + - <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a> + + +<a name="api_nan_error"></a> +### Nan::Error() + +Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::Error(const char *msg); +v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_range_error"></a> +### Nan::RangeError() + +Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an RangeError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::RangeError(const char *msg); +v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_reference_error"></a> +### Nan::ReferenceError() + +Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an ReferenceError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::ReferenceError(const char *msg); +v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_syntax_error"></a> +### Nan::SyntaxError() + +Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an SyntaxError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::SyntaxError(const char *msg); +v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_type_error"></a> +### Nan::TypeError() + +Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an TypeError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::TypeError(const char *msg); +v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_throw_error"></a> +### Nan::ThrowError() + +Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created. + +Signature: + +```c++ +void Nan::ThrowError(const char *msg); +void Nan::ThrowError(v8::Local<v8::String> msg); +void Nan::ThrowError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_range_error"></a> +### Nan::ThrowRangeError() + +Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created. + +Signature: + +```c++ +void Nan::ThrowRangeError(const char *msg); +void Nan::ThrowRangeError(v8::Local<v8::String> msg); +void Nan::ThrowRangeError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_reference_error"></a> +### Nan::ThrowReferenceError() + +Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created. + +Signature: + +```c++ +void Nan::ThrowReferenceError(const char *msg); +void Nan::ThrowReferenceError(v8::Local<v8::String> msg); +void Nan::ThrowReferenceError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_syntax_error"></a> +### Nan::ThrowSyntaxError() + +Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created. + +Signature: + +```c++ +void Nan::ThrowSyntaxError(const char *msg); +void Nan::ThrowSyntaxError(v8::Local<v8::String> msg); +void Nan::ThrowSyntaxError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_type_error"></a> +### Nan::ThrowTypeError() + +Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created. + +Signature: + +```c++ +void Nan::ThrowTypeError(const char *msg); +void Nan::ThrowTypeError(v8::Local<v8::String> msg); +void Nan::ThrowTypeError(v8::Local<v8::Value> error); +``` + +<a name="api_nan_fatal_exception"></a> +### Nan::FatalException() + +Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch). + +Signature: + +```c++ +void Nan::FatalException(const Nan::TryCatch& try_catch); +``` + +<a name="api_nan_errno_exception"></a> +### Nan::ErrnoException() + +Replaces `node::ErrnoException()` which has a different API across supported versions of Node. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::ErrnoException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL); +``` + + +<a name="api_nan_try_catch"></a> +### Nan::TryCatch + +A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/io.js-3.3/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`. + +Signature: + +```c++ +class Nan::TryCatch { + public: + Nan::TryCatch(); + + bool HasCaught() const; + + bool CanContinue() const; + + v8::Local<v8::Value> ReThrow(); + + v8::Local<v8::Value> Exception() const; + + // Nan::MaybeLocal for older versions of V8 + v8::MaybeLocal<v8::Value> StackTrace() const; + + v8::Local<v8::Message> Message() const; + + void Reset(); + + void SetVerbose(bool value); + + void SetCaptureMessage(bool value); +}; +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/json.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/json.md new file mode 100644 index 0000000000000000000000000000000000000000..c916c4d158cdcf926016a4e9e992ca3f3386fda0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/json.md @@ -0,0 +1,62 @@ +## JSON + +The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. + + - <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> + - <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> + +Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. + +<a name="api_nan_json_parse"></a> + +### Nan::JSON.Parse + +A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504). + +Definition: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string); +``` + +Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`. + +Example: + +```c++ +v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked(); + +Nan::JSON NanJSON; +Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string); +if (!result.IsEmpty()) { + v8::Local<v8::Value> val = result.ToLocalChecked(); +} +``` + +<a name="api_nan_json_stringify"></a> + +### Nan::JSON.Stringify + +A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860). + +Definition: + +```c++ +Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>()); +``` + +Use `JSON.Stringify(value)` to stringify a `v8::Object`. + +Example: + +```c++ +// using `v8::Local<v8::Value> val` from the `JSON::Parse` example +v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked(); + +Nan::JSON NanJSON; +Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj); +if (!result.IsEmpty()) { + v8::Local<v8::String> stringified = result.ToLocalChecked(); +} +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/maybe_types.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/maybe_types.md new file mode 100644 index 0000000000000000000000000000000000000000..f11df56d9297ad03f154281e17a268aa60f98f80 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/maybe_types.md @@ -0,0 +1,583 @@ +## Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a> + - <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a> + - <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a> + - <a href="#api_nan_just"><b><code>Nan::Just</code></b></a> +* **Maybe Helpers** + - <a href="#api_nan_call"><b><code>Nan::Call()</code></b></a> + - <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a> + - <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a> + - <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a> + - <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a> + - <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a> + - <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a> + - <a href="#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a> + - <a href="#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a> + - <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a> + - <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a> + - <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a> + - <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a> + - <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a> + - <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a> + - <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a> + - <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a> + - <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a> + - <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a> + - <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a> + - <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a> + - <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a> + - <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a> + - <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a> + - <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a> + - <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a> + - <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a> + - <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a> + - <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a> + - <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a> + - <a href="#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a> + - <a href="#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a> + - <a href="#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a> + - <a href="#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a> + - <a href="#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a> + +<a name="api_nan_maybe_local"></a> +### Nan::MaybeLocal + +A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/io.js-3.3/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used. + +If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned. + +Definition: + +```c++ +template<typename T> class Nan::MaybeLocal { + public: + MaybeLocal(); + + template<typename S> MaybeLocal(v8::Local<S> that); + + bool IsEmpty() const; + + template<typename S> bool ToLocal(v8::Local<S> *out); + + // Will crash if the MaybeLocal<> is empty. + v8::Local<T> ToLocalChecked(); + + template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const; +}; +``` + +See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/io.js-3.3/d8/d7d/classv8_1_1_maybe_local.html) for further details. + +<a name="api_nan_maybe"></a> +### Nan::Maybe + +A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html. + +If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned. + +Definition: + +```c++ +template<typename T> class Nan::Maybe { + public: + bool IsNothing() const; + bool IsJust() const; + + // Will crash if the Maybe<> is nothing. + T FromJust(); + + T FromMaybe(const T& default_value); + + bool operator==(const Maybe &other); + + bool operator!=(const Maybe &other); +}; +``` + +See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/io.js-3.3/d9/d4b/classv8_1_1_maybe.html) for further details. + +<a name="api_nan_nothing"></a> +### Nan::Nothing + +Construct an empty `Nan::Maybe` type representing _nothing_. + +```c++ +template<typename T> Nan::Maybe<T> Nan::Nothing(); +``` + +<a name="api_nan_just"></a> +### Nan::Just + +Construct a `Nan::Maybe` type representing _just_ a value. + +```c++ +template<typename T> Nan::Maybe<T> Nan::Just(const T &t); +``` + +<a name="api_nan_call"></a> +### Nan::Call() + +A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/io.js-3.3/d5/d54/classv8_1_1_function.html#a468a89f737af0612db10132799c827c0) in a way compatible across supported versions of V8. + +For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::Call(v8::Local<v8::Function> fun, v8::Local<v8::Object> recv, int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, v8::Local<v8::Object> recv, + int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, int argc, v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_to_detail_string"></a> +### Nan::ToDetailString() + +A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val); +``` + + +<a name="api_nan_to_array_index"></a> +### Nan::ToArrayIndex() + +A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val); +``` + + +<a name="api_nan_equals"></a> +### Nan::Equals() + +A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#a0d9616ab2de899d4e3047c30a10c9285) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)); +``` + + +<a name="api_nan_new_instance"></a> +### Nan::NewInstance() + +A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/io.js-3.3/d5/d54/classv8_1_1_function.html#a691b13f7a553069732cbacf5ac8c62ec) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/io.js-3.3/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h); +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h); +``` + + +<a name="api_nan_get_function"></a> +### Nan::GetFunction() + +A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/io.js-3.3/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t); +``` + + +<a name="api_nan_set"></a> +### Nan::Set() + +A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key, + v8::Local<v8::Value> value) +Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj, + uint32_t index, + v8::Local<v8::Value> value); +``` + + +<a name="api_nan_define_own_property"></a> +### Nan::DefineOwnProperty() + +A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-4.8/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::DefineOwnProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key, + v8::Local<v8::Value> value, + v8::PropertyAttribute attribs = v8::None); +``` + + +<a name="api_nan_force_set"></a> +### <del>Nan::ForceSet()</del> + +Deprecated, use <a href="#api_nan_define_own_property"><code>Nan::DefineOwnProperty()</code></a>. + +<del>A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a796b7b682896fb64bf1872747734e836) in a way compatible across supported versions of V8.</del> + +Signature: + +```c++ +NAN_DEPRECATED Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key, + v8::Local<v8::Value> value, + v8::PropertyAttribute attribs = v8::None); +``` + + +<a name="api_nan_get"></a> +### Nan::Get() + +A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key); +Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_get_property_attribute"></a> +### Nan::GetPropertyAttributes() + +A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes( + v8::Local<v8::Object> obj, + v8::Local<v8::Value> key); +``` + + +<a name="api_nan_has"></a> +### Nan::Has() + +A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key); +Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_delete"></a> +### Nan::Delete() + +A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a2fa0f5a592582434ed1ceceff7d891ef) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_get_property_names"></a> +### Nan::GetPropertyNames() + +A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_get_own_property_names"></a> +### Nan::GetOwnPropertyNames() + +A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_set_prototype"></a> +### Nan::SetPrototype() + +A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj, + v8::Local<v8::Value> prototype); +``` + + +<a name="api_nan_object_proto_to_string"></a> +### Nan::ObjectProtoToString() + +A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_has_own_property"></a> +### Nan::HasOwnProperty() + +A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_has_real_named_property"></a> +### Nan::HasRealNamedProperty() + +A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_has_real_indexed_property"></a> +### Nan::HasRealIndexedProperty() + +A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj, + uint32_t index); +``` + + +<a name="api_nan_has_real_named_callback_property"></a> +### Nan::HasRealNamedCallbackProperty() + +A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty( + v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_get_real_named_property_in_prototype_chain"></a> +### Nan::GetRealNamedPropertyInPrototypeChain() + +A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain( + v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_get_real_named_property"></a> +### Nan::GetRealNamedProperty() + +A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_call_as_function"></a> +### Nan::CallAsFunction() + +A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a9ef18be634e79b4f0cdffa1667a29f58) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj, + v8::Local<v8::Object> recv, + int argc, + v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_call_as_constructor"></a> +### Nan::CallAsConstructor() + +A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj, + int argc, + v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_get_source_line"></a> +### Nan::GetSourceLine() + +A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_line_number"></a> +### Nan::GetLineNumber() + +A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_start_column"></a> +### Nan::GetStartColumn() + +A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_end_column"></a> +### Nan::GetEndColumn() + +A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_clone_element_at"></a> +### Nan::CloneElementAt() + +A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/io.js-3.3/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index); +``` + +<a name="api_nan_has_private"></a> +### Nan::HasPrivate() + +A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_get_private"></a> +### Nan::GetPrivate() + +A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_set_private"></a> +### Nan::SetPrivate() + +A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value); +``` + +<a name="api_nan_delete_private"></a> +### Nan::DeletePrivate() + +A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::DeletePrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_make_maybe"></a> +### Nan::MakeMaybe() + +Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN. + +Synopsis: + +```c++ + MaybeLocal<v8::Number> someNumber = MakeMaybe(New<v8::Number>(3.141592654)); + MaybeLocal<v8::String> someString = MakeMaybe(New<v8::String>("probably")); +``` + +Signature: + +```c++ +template <typename T, template <typename> class MaybeMaybe> +Nan::MaybeLocal<T> Nan::MakeMaybe(MaybeMaybe<T> v); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/methods.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/methods.md new file mode 100644 index 0000000000000000000000000000000000000000..bae46f26f30cac36e52260087c87cb2cd223d72f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/methods.md @@ -0,0 +1,659 @@ +## JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a> + - <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a> + - <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a> +* **Method declarations** + - <a href="#api_nan_method"><b>Method declaration</b></a> + - <a href="#api_nan_getter"><b>Getter declaration</b></a> + - <a href="#api_nan_setter"><b>Setter declaration</b></a> + - <a href="#api_nan_property_getter"><b>Property getter declaration</b></a> + - <a href="#api_nan_property_setter"><b>Property setter declaration</b></a> + - <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a> + - <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a> + - <a href="#api_nan_property_query"><b>Property query declaration</b></a> + - <a href="#api_nan_index_getter"><b>Index getter declaration</b></a> + - <a href="#api_nan_index_setter"><b>Index setter declaration</b></a> + - <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a> + - <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a> + - <a href="#api_nan_index_query"><b>Index query declaration</b></a> +* Method and template helpers + - <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a> + - <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a> + - <a href="#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a> + - <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a> + - <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a> + - <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a> + - <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a> + - <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a> + - <a href="#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a> + - <a href="#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a> + +<a name="api_nan_function_callback_info"></a> +### Nan::FunctionCallbackInfo + +`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.0/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist. + +Definition: + +```c++ +template<typename T> class FunctionCallbackInfo { + public: + ReturnValue<T> GetReturnValue() const; + v8::Local<v8::Function> Callee(); + v8::Local<v8::Value> Data(); + v8::Local<v8::Object> Holder(); + bool IsConstructCall(); + int Length() const; + v8::Local<v8::Value> operator[](int i) const; + v8::Local<v8::Object> This() const; + v8::Isolate *GetIsolate() const; +}; +``` + +See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.0/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods. + +<a name="api_nan_property_callback_info"></a> +### Nan::PropertyCallbackInfo + +`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.0/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist. + +Definition: + +```c++ +template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> { + public: + ReturnValue<T> GetReturnValue() const; + v8::Isolate* GetIsolate() const; + v8::Local<v8::Value> Data() const; + v8::Local<v8::Object> This() const; + v8::Local<v8::Object> Holder() const; +}; +``` + +See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.0/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods. + +<a name="api_nan_return_value"></a> +### Nan::ReturnValue + +`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.0/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`. + +Example usage: + +```c++ +void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { + info.GetReturnValue().Set(Nan::New<v8::Array>()); +} +``` + +Definition: + +```c++ +template<typename T> class ReturnValue { + public: + // Handle setters + template <typename S> void Set(const v8::Local<S> &handle); + template <typename S> void Set(const Nan::Global<S> &handle); + + // Fast primitive setters + void Set(bool value); + void Set(double i); + void Set(int32_t i); + void Set(uint32_t i); + + // Fast JS primitive setters + void SetNull(); + void SetUndefined(); + void SetEmptyString(); + + // Convenience getter for isolate + v8::Isolate *GetIsolate() const; +}; +``` + +See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.0/da/da7/classv8_1_1_return_value.html) for further information on this. + +<a name="api_nan_method"></a> +### Method declaration + +JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`: + +```c++ +typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a method as one is implicitly created for you. + +**Example usage** + +```c++ +// .h: +class Foo : public Nan::ObjectWrap { + ... + + static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info); + static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info); +} + + +// .cc: +void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} + +void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} +``` + +A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations. + +**Example usage with `NAN_METHOD(methodname)`** + +```c++ +// .h: +class Foo : public Nan::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object. + +<a name="api_nan_getter"></a> +### Getter declaration + +JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`: + +```c++ +typedef void(*GetterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void GetterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you. + +A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). + +<a name="api_nan_setter"></a> +### Setter declaration + +JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>: + +```c++ +typedef void(*SetterCallback)(v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<void>&); +``` + +Example: + +```c++ +void SetterName(v8::Local<v8::String> property, + v8::Local<v8::Value> value, + const Nan::PropertyCallbackInfo<void>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you. + +A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). + +<a name="api_nan_property_getter"></a> +### Property getter declaration + +JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>: + +```c++ +typedef void(*PropertyGetterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void PropertyGetterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_setter"></a> +### Property setter declaration + +JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>: + +```c++ +typedef void(*PropertySetterCallback)(v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void PropertySetterName(v8::Local<v8::String> property, + v8::Local<v8::Value> value, + const Nan::PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_enumerator"></a> +### Property enumerator declaration + +JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>: + +```c++ +typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&); +``` + +Example: + +```c++ +void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info); +``` + +You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_deleter"></a> +### Property deleter declaration + +JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>: + +```c++ +typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Boolean>&); +``` + +Example: + +```c++ +void PropertyDeleterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Boolean>& info); +``` + +You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_query"></a> +### Property query declaration + +JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>: + +```c++ +typedef void(*PropertyQueryCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Integer>&); +``` + +Example: + +```c++ +void PropertyQueryName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Integer>& info); +``` + +You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_getter"></a> +### Index getter declaration + +JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>: + +```c++ +typedef void(*IndexGetterCallback)(uint32_t, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you. + +A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_setter"></a> +### Index setter declaration + +JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>: + +```c++ +typedef void(*IndexSetterCallback)(uint32_t, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void IndexSetterName(uint32_t index, + v8::Local<v8::Value> value, + const PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you. + +A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_enumerator"></a> +### Index enumerator declaration + +JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>: + +```c++ +typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&); +``` + +Example: + +```c++ +void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info); +``` + +You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you. + +A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_deleter"></a> +### Index deleter declaration + +JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>: + +```c++ +typedef void(*IndexDeleterCallback)(uint32_t, + const PropertyCallbackInfo<v8::Boolean>&); +``` + +Example: + +```c++ +void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info); +``` + +You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you. + +A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_query"></a> +### Index query declaration + +JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>: + +```c++ +typedef void(*IndexQueryCallback)(uint32_t, + const PropertyCallbackInfo<v8::Integer>&); +``` + +Example: + +```c++ +void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info); +``` + +You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you. + +A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_set_method"></a> +### Nan::SetMethod() + +Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>). + +Signature: + +```c++ +void Nan::SetMethod(v8::Local<v8::Object> recv, + const char *name, + Nan::FunctionCallback callback) +void Nan::SetMethod(v8::Local<v8::Template> templ, + const char *name, + Nan::FunctionCallback callback) +``` + +<a name="api_nan_set_prototype_method"></a> +### Nan::SetPrototypeMethod() + +Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>). + +Signature: + +```c++ +void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv, + const char* name, + Nan::FunctionCallback callback) +``` + +<a name="api_nan_set_accessor"></a> +### Nan::SetAccessor() + +Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>). + +Signature: + +```c++ +void SetAccessor(v8::Local<v8::ObjectTemplate> tpl, + v8::Local<v8::String> name, + Nan::GetterCallback getter, + Nan::SetterCallback setter = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + v8::AccessControl settings = v8::DEFAULT, + v8::PropertyAttribute attribute = v8::None, + imp::Sig signature = imp::Sig()); +bool SetAccessor(v8::Local<v8::Object> obj, + v8::Local<v8::String> name, + Nan::GetterCallback getter, + Nan::SetterCallback setter = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + v8::AccessControl settings = v8::DEFAULT, + v8::PropertyAttribute attribute = v8::None) +``` + +See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.0/db/d85/classv8_1_1_object.html#a3f9dee085f5ec346465f1dc924325043) for further information about how to use `Nan::SetAccessor()`. + +<a name="api_nan_set_named_property_handler"></a> +### Nan::SetNamedPropertyHandler() + +Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: + +* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>) +* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>) +* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>) +* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>) +* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>) + +Signature: + +```c++ +void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl, + Nan::PropertyGetterCallback getter, + Nan::PropertySetterCallback setter = 0, + Nan::PropertyQueryCallback query = 0, + Nan::PropertyDeleterCallback deleter = 0, + Nan::PropertyEnumeratorCallback enumerator = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/io.js-3.3/db/d5f/classv8_1_1_object_template.html#a34d1cc45b642cd131706663801aadd76) for further information about how to use `Nan::SetNamedPropertyHandler()`. + +<a name="api_nan_set_indexed_property_handler"></a> +### Nan::SetIndexedPropertyHandler() + +Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: + +* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>) +* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>) +* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>) +* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>) +* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>) + +Signature: + +```c++ +void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl, + Nan::IndexGetterCallback getter, + Nan::IndexSetterCallback setter = 0, + Nan::IndexQueryCallback query = 0, + Nan::IndexDeleterCallback deleter = 0, + Nan::IndexEnumeratorCallback enumerator = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`. + +<a name="api_nan_set_template"></a> +### Nan::SetTemplate() + +Adds properties on an `Object`'s or `Function`'s template. + +Signature: + +```c++ +void Nan::SetTemplate(v8::Local<v8::Template> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetTemplate(v8::Local<v8::Template> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.0/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac). + +<a name="api_nan_set_prototype_template"></a> +### Nan::SetPrototypeTemplate() + +Adds properties on an `Object`'s or `Function`'s prototype template. + +Signature: + +```c++ +void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.3/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). + +<a name="api_nan_set_instance_template"></a> +### Nan::SetInstanceTemplate() + +Use to add instance properties on `FunctionTemplate`'s. + +Signature: + +```c++ +void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.3/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). + +<a name="api_nan_set_call_handler"></a> +### Nan::SetCallHandler() + +Set the call-handler callback for a `v8::FunctionTemplate`. +This callback is called whenever the function created from this FunctionTemplate is called. + +Signature: + +```c++ +void Nan::SetCallHandler(v8::Local<v8::FunctionTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.0/d8/d83/classv8_1_1_function_template.html#a2d3845db66392074c5a018a66efbfada). + +<a name="api_nan_set_call_as_function_handler"></a> +### Nan::SetCallAsFunctionHandler() + +Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function. +If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function. + +Signature: + +```c++ +void Nan::SetCallAsFunctionHandler(v8::Local<v8::ObjectTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/new.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/new.md new file mode 100644 index 0000000000000000000000000000000000000000..0804b62f9ef5e939fd942d82f4d15b20560e8b15 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/new.md @@ -0,0 +1,147 @@ +## New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - <a href="#api_nan_new"><b><code>Nan::New()</code></b></a> + - <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a> + - <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a> + - <a href="#api_nan_true"><b><code>Nan::True()</code></b></a> + - <a href="#api_nan_false"><b><code>Nan::False()</code></b></a> + - <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a> + + +<a name="api_nan_new"></a> +### Nan::New() + +`Nan::New()` should be used to instantiate new JavaScript objects. + +Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/io.js-3.3/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation. + +Signatures: + +Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`. + +Empty objects: + +```c++ +Nan::New<T>(); +``` + +Generic single and multiple-argument: + +```c++ +Nan::New<T>(A0 arg0); +Nan::New<T>(A0 arg0, A1 arg1); +Nan::New<T>(A0 arg0, A1 arg1, A2 arg2); +Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3); +``` + +For creating `v8::FunctionTemplate` and `v8::Function` objects: + +_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._ + +```c++ +Nan::New<T>(Nan::FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>()); +Nan::New<T>(Nan::FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + A2 a2 = A2()); +``` + +Native number types: + +```c++ +v8::Local<v8::Boolean> Nan::New<T>(bool value); +v8::Local<v8::Int32> Nan::New<T>(int32_t value); +v8::Local<v8::Uint32> Nan::New<T>(uint32_t value); +v8::Local<v8::Number> Nan::New<T>(double value); +``` + +String types: + +```c++ +Nan::MaybeLocal<v8::String> Nan::New<T>(std::string const& value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value, int length); +Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value, int length); +``` + +Specialized types: + +```c++ +v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value); +v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value); +v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags); +``` + +Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/io.js-3.3/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8. + + +<a name="api_nan_undefined"></a> +### Nan::Undefined() + +A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Primitive> Nan::Undefined() +``` + +<a name="api_nan_null"></a> +### Nan::Null() + +A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Primitive> Nan::Null() +``` + +<a name="api_nan_true"></a> +### Nan::True() + +A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Boolean> Nan::True() +``` + +<a name="api_nan_false"></a> +### Nan::False() + +A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Boolean> Nan::False() +``` + +<a name="api_nan_empty_string"></a> +### Nan::EmptyString() + +Call [`v8::String::Empty`](https://v8docs.nodesource.com/io.js-3.3/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::String> Nan::EmptyString() +``` + + +<a name="api_nan_new_one_byte_string"></a> +### Nan::NewOneByteString() + +An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/io.js-3.3/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value, + int length = -1) +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/node_misc.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/node_misc.md new file mode 100644 index 0000000000000000000000000000000000000000..11a1990a4fb50ffd606abce2b5d8162972fd1e54 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/node_misc.md @@ -0,0 +1,123 @@ +## Miscellaneous Node Helpers + + - <a href="#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a> + - <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a> + - <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a> + - <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a> + +<a name="api_nan_asyncresource"></a> +### Nan::AsyncResource + +This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API. + +When calling back into JavaScript asynchornously, special care must be taken to ensure that the runtime can properly track +async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`, +and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or +`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms +such as domains and [async_hooks][] function correctly. + +Definition: + +```c++ +class AsyncResource { + public: + AsyncResource(v8::Local<v8::String> name, + v8::Local<v8::Object> resource = New<v8::Object>()); + AsyncResource(const char* name, + v8::Local<v8::Object> resource = New<v8::Object>()); + ~AsyncResource(); + + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); +}; +``` + +* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][] + API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend + that the name include the name of the owning module as a prefix. For example `mysql` module could use something like + `mysql:batch-db-query-resource`. +* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][] + `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically. +* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the + correct async execution context. +* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed. + +For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the +[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory. + +<a name="api_nan_make_callback"></a> +### Nan::MakeCallback() + +Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+ +has deprecated these legacy APIs as they do not provide a mechanism to preserve +async context. + +We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or +`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution +context – something that is essential for functionality like domains, async_hooks and async debugging. + +Signatures: + +```c++ +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); +``` + + +<a name="api_nan_module_init"></a> +### NAN_MODULE_INIT() + +Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object. + +See example below. + +<a name="api_nan_export"></a> +### Nan::Export() + +A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript. + +Signature: + +```c++ +void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f) +``` + +Also available as the shortcut `NAN_EXPORT` macro. + +Example: + +```c++ +NAN_METHOD(Foo) { + ... +} + +NAN_MODULE_INIT(Init) { + NAN_EXPORT(target, Foo); +} +``` + +[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html +[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/object_wrappers.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/object_wrappers.md new file mode 100644 index 0000000000000000000000000000000000000000..e89832b65dd4507071f647458e3272f4c0c65425 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/object_wrappers.md @@ -0,0 +1,263 @@ +## Object Wrappers + +The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. + + - <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a> + + +<a name="api_nan_object_wrap"></a> +### Nan::ObjectWrap() + +A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency. + +Definition: + +```c++ +class ObjectWrap { + public: + ObjectWrap(); + + virtual ~ObjectWrap(); + + template <class T> + static inline T* Unwrap(v8::Local<v8::Object> handle); + + inline v8::Local<v8::Object> handle(); + + inline Nan::Persistent<v8::Object>& persistent(); + + protected: + inline void Wrap(v8::Local<v8::Object> handle); + + inline void MakeWeak(); + + /* Ref() marks the object as being attached to an event loop. + * Refed objects will not be garbage collected, even if + * all references are lost. + */ + virtual void Ref(); + + /* Unref() marks an object as detached from the event loop. This is its + * default state. When an object with a "weak" reference changes from + * attached to detached state it will be freed. Be careful not to access + * the object after making this call as it might be gone! + * (A "weak reference" means an object that only has a + * persistant handle.) + * + * DO NOT CALL THIS FROM DESTRUCTOR + */ + virtual void Unref(); + + int refs_; // ro +}; +``` + +See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details. + +### This vs. Holder + +When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class. +The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance. +In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected. +However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain. +In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption. + +On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype. +So either define your accessors on the instance template, +or use `This()` after verifying that it is indeed a valid object. + +### Examples + +#### Basic + +```c++ +class MyObject : public Nan::ObjectWrap { + public: + static NAN_MODULE_INIT(Init) { + v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); + tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); + Nan::SetPrototypeMethod(tpl, "getValue", GetValue); + + constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); + Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), + Nan::GetFunction(tpl).ToLocalChecked()); + } + + private: + explicit MyObject(double value = 0) : value_(value) {} + ~MyObject() {} + + static NAN_METHOD(New) { + if (info.IsConstructCall()) { + double value = info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust(); + MyObject *obj = new MyObject(value); + obj->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } else { + const int argc = 1; + v8::Local<v8::Value> argv[argc] = {info[0]}; + v8::Local<v8::Function> cons = Nan::New(constructor()); + info.GetReturnValue().Set(cons->NewInstance(argc, argv)); + } + } + + static NAN_METHOD(GetHandle) { + MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder()); + info.GetReturnValue().Set(obj->handle()); + } + + static NAN_METHOD(GetValue) { + MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder()); + info.GetReturnValue().Set(obj->value_); + } + + static inline Nan::Persistent<v8::Function> & constructor() { + static Nan::Persistent<v8::Function> my_constructor; + return my_constructor; + } + + double value_; +}; + +NODE_MODULE(objectwrapper, MyObject::Init) +``` + +To use in Javascript: + +```Javascript +var objectwrapper = require('bindings')('objectwrapper'); + +var obj = new objectwrapper.MyObject(5); +console.log('Should be 5: ' + obj.getValue()); +``` + +#### Factory of wrapped objects + +```c++ +class MyFactoryObject : public Nan::ObjectWrap { + public: + static NAN_MODULE_INIT(Init) { + v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + Nan::SetPrototypeMethod(tpl, "getValue", GetValue); + + constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); + } + + static NAN_METHOD(NewInstance) { + v8::Local<v8::Function> cons = Nan::New(constructor()); + double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0; + const int argc = 1; + v8::Local<v8::Value> argv[1] = {Nan::New(value)}; + info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); + } + + // Needed for the next example: + inline double value() const { + return value_; + } + + private: + explicit MyFactoryObject(double value = 0) : value_(value) {} + ~MyFactoryObject() {} + + static NAN_METHOD(New) { + if (info.IsConstructCall()) { + double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0; + MyFactoryObject * obj = new MyFactoryObject(value); + obj->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } else { + const int argc = 1; + v8::Local<v8::Value> argv[argc] = {info[0]}; + v8::Local<v8::Function> cons = Nan::New(constructor()); + info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); + } + } + + static NAN_METHOD(GetValue) { + MyFactoryObject* obj = ObjectWrap::Unwrap<MyFactoryObject>(info.Holder()); + info.GetReturnValue().Set(obj->value_); + } + + static inline Nan::Persistent<v8::Function> & constructor() { + static Nan::Persistent<v8::Function> my_constructor; + return my_constructor; + } + + double value_; +}; + +NAN_MODULE_INIT(Init) { + MyFactoryObject::Init(target); + Nan::Set(target, + Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(), + Nan::GetFunction( + Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked() + ); +} + +NODE_MODULE(wrappedobjectfactory, Init) +``` + +To use in Javascript: + +```Javascript +var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); + +var obj = wrappedobjectfactory.newFactoryObjectInstance(10); +console.log('Should be 10: ' + obj.getValue()); +``` + +#### Passing wrapped objects around + +Use the `MyFactoryObject` class above along with the following: + +```c++ +static NAN_METHOD(Sum) { + Nan::MaybeLocal<v8::Object> maybe1 = Nan::To<v8::Object>(info[0]); + Nan::MaybeLocal<v8::Object> maybe2 = Nan::To<v8::Object>(info[1]); + + // Quick check: + if (maybe1.IsEmpty() || maybe2.IsEmpty()) { + // return value is undefined by default + return; + } + + MyFactoryObject* obj1 = + Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe1.ToLocalChecked()); + MyFactoryObject* obj2 = + Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe2.ToLocalChecked()); + + info.GetReturnValue().Set(Nan::New<v8::Number>(obj1->value() + obj2->value())); +} + +NAN_MODULE_INIT(Init) { + MyFactoryObject::Init(target); + Nan::Set(target, + Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(), + Nan::GetFunction( + Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked() + ); + Nan::Set(target, + Nan::New<v8::String>("sum").ToLocalChecked(), + Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Sum)).ToLocalChecked() + ); +} + +NODE_MODULE(myaddon, Init) +``` + +To use in Javascript: + +```Javascript +var myaddon = require('bindings')('myaddon'); + +var obj1 = myaddon.newFactoryObjectInstance(5); +var obj2 = myaddon.newFactoryObjectInstance(10); +console.log('sum of object values: ' + myaddon.sum(obj1, obj2)); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/persistent.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/persistent.md new file mode 100644 index 0000000000000000000000000000000000000000..f6ebefa0b991b549efcf7ff39cd932d4b30c05ab --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/persistent.md @@ -0,0 +1,295 @@ +## Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a> + - <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a> + - <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a> + - <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a> + - <a href="#api_nan_global"><b><code>Nan::Global</code></b></a> + - <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a> + - <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +<a name="api_nan_persistent_base"></a> +### Nan::PersistentBase & v8::PersistentBase + +A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`. + +Definition: + +_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_ + +```c++ +template<typename T> class PersistentBase { + public: + /** + * If non-empty, destroy the underlying storage cell + */ + void Reset(); + + /** + * If non-empty, destroy the underlying storage cell and create a new one with + * the contents of another if it is also non-empty + */ + template<typename S> void Reset(const v8::Local<S> &other); + + /** + * If non-empty, destroy the underlying storage cell and create a new one with + * the contents of another if it is also non-empty + */ + template<typename S> void Reset(const PersistentBase<S> &other); + + /** + * If non-empty, destroy the underlying storage cell + * IsEmpty() will return true after this call. + */ + bool IsEmpty(); + + void Empty(); + + template<typename S> bool operator==(const PersistentBase<S> &that); + + template<typename S> bool operator==(const v8::Local<S> &that); + + template<typename S> bool operator!=(const PersistentBase<S> &that); + + template<typename S> bool operator!=(const v8::Local<S> &that); + + /** + * Install a finalization callback on this object. + * NOTE: There is no guarantee as to *when* or even *if* the callback is + * invoked. The invocation is performed solely on a best effort basis. + * As always, GC-based finalization should *not* be relied upon for any + * critical form of resource management! At the moment you can either + * specify a parameter for the callback or the location of two internal + * fields in the dying object. + */ + template<typename P> + void SetWeak(P *parameter, + typename WeakCallbackInfo<P>::Callback callback, + WeakCallbackType type); + + void ClearWeak(); + + /** + * Marks the reference to this object independent. Garbage collector is free + * to ignore any object groups containing this object. Weak callback for an + * independent handle should not assume that it will be preceded by a global + * GC prologue callback or followed by a global GC epilogue callback. + */ + void MarkIndependent() const; + + bool IsIndependent() const; + + /** Checks if the handle holds the only reference to an object. */ + bool IsNearDeath() const; + + /** Returns true if the handle's reference is weak. */ + bool IsWeak() const +}; +``` + +See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/io.js-3.3/d4/dca/classv8_1_1_persistent_base.html) for further information. + +**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object: + +```c++ +v8::Local<v8::Object> object = Nan::New(persistent); +``` + +<a name="api_nan_non_copyable_persistent_traits"></a> +### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits + +Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version. + +Definition: + +_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ + +```c++ +template<typename T> class NonCopyablePersistentTraits { + public: + typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent; + + static const bool kResetInDestructor = false; + + template<typename S, typename M> + static void Copy(const Persistent<S, M> &source, + NonCopyablePersistent *dest); + + template<typename O> static void Uncompilable(); +}; +``` + +See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.3/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information. + +<a name="api_nan_copyable_persistent_traits"></a> +### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits + +A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc.. + +Definition: + +_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ + +```c++ +template<typename T> +class CopyablePersistentTraits { + public: + typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent; + + static const bool kResetInDestructor = true; + + template<typename S, typename M> + static void Copy(const Persistent<S, M> &source, + CopyablePersistent *dest); +}; +``` + +See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.3/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information. + +<a name="api_nan_persistent"></a> +### Nan::Persistent + +A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`. + +Definition: + +```c++ +template<typename T, typename M = NonCopyablePersistentTraits<T> > +class Persistent; + +template<typename T, typename M> class Persistent : public PersistentBase<T> { + public: + /** + * A Persistent with no storage cell. + */ + Persistent(); + + /** + * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a + * new storage cell is created pointing to the same object, and no flags are + * set. + */ + template<typename S> Persistent(v8::Local<S> that); + + /** + * Construct a Persistent from a Persistent. When the Persistent is non-empty, + * a new storage cell is created pointing to the same object, and no flags are + * set. + */ + Persistent(const Persistent &that); + + /** + * The copy constructors and assignment operator create a Persistent exactly + * as the Persistent constructor, but the Copy function from the traits class + * is called, allowing the setting of flags based on the copied Persistent. + */ + Persistent &operator=(const Persistent &that); + + template <typename S, typename M2> + Persistent &operator=(const Persistent<S, M2> &that); + + /** + * The destructor will dispose the Persistent based on the kResetInDestructor + * flags in the traits class. Since not calling dispose can result in a + * memory leak, it is recommended to always set this flag. + */ + ~Persistent(); +}; +``` + +See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/io.js-3.3/d2/d78/classv8_1_1_persistent.html) for further information. + +<a name="api_nan_global"></a> +### Nan::Global + +A type of `PersistentBase` which has move semantics. + +```c++ +template<typename T> class Global : public PersistentBase<T> { + public: + /** + * A Global with no storage cell. + */ + Global(); + + /** + * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new + * storage cell is created pointing to the same object, and no flags are set. + */ + template<typename S> Global(v8::Local<S> that); + /** + * Construct a Global from a PersistentBase. When the Persistent is non-empty, + * a new storage cell is created pointing to the same object, and no flags are + * set. + */ + template<typename S> Global(const PersistentBase<S> &that); + + /** + * Pass allows returning globals from functions, etc. + */ + Global Pass(); +}; +``` + +See the V8 documentation for [`Global`](https://v8docs.nodesource.com/io.js-3.3/d5/d40/classv8_1_1_global.html) for further information. + +<a name="api_nan_weak_callback_info"></a> +### Nan::WeakCallbackInfo + +`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8. + +Definition: + +```c++ +template<typename T> class WeakCallbackInfo { + public: + typedef void (*Callback)(const WeakCallbackInfo<T>& data); + + v8::Isolate *GetIsolate() const; + + /** + * Get the parameter that was associated with the weak handle. + */ + T *GetParameter() const; + + /** + * Get pointer from internal field, index can be 0 or 1. + */ + void *GetInternalField(int index) const; +}; +``` + +Example usage: + +```c++ +void weakCallback(const WeakCallbackInfo<int> &data) { + int *parameter = data.GetParameter(); + delete parameter; +} + +Persistent<v8::Object> obj; +int *data = new int(0); +obj.SetWeak(data, callback, WeakCallbackType::kParameter); +``` + +See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/io.js-3.3/d8/d06/classv8_1_1_weak_callback_info.html) for further information. + +<a name="api_nan_weak_callback_type"></a> +### Nan::WeakCallbackType + +Represents the type of a weak callback. +A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`. +A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak. +Note that only `v8::Object`s and derivatives can have internal fields. + +Definition: + +```c++ +enum class WeakCallbackType { kParameter, kInternalFields }; +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/scopes.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/scopes.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfb417c6097d059380750b22c2219b9cd497dc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/scopes.md @@ -0,0 +1,73 @@ +## Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> + - <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). + +<a name="api_nan_handle_scope"></a> +### Nan::HandleScope + +A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/io.js-3.3/d3/d95/classv8_1_1_handle_scope.html). + +Definition: + +```c++ +class Nan::HandleScope { + public: + Nan::HandleScope(); + static int NumberOfHandles(); +}; +``` + +Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself. + +Example: + +```c++ +// new object is created, it needs a new scope: +void Pointless() { + Nan::HandleScope scope; + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); +} + +// JavaScript-accessible method already has a HandleScope +NAN_METHOD(Pointless2) { + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); +} +``` + +<a name="api_nan_escapable_handle_scope"></a> +### Nan::EscapableHandleScope + +Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it. + +Definition: + +```c++ +class Nan::EscapableHandleScope { + public: + Nan::EscapableHandleScope(); + static int NumberOfHandles(); + template<typename T> v8::Local<T> Escape(v8::Local<T> value); +} +``` + +Use `Escape(value)` to return the object. + +Example: + +```c++ +v8::Local<v8::Object> EmptyObj() { + Nan::EscapableHandleScope scope; + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); + return scope.Escape(obj); +} +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/script.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/script.md new file mode 100644 index 0000000000000000000000000000000000000000..e518505ec2b82ad7b4d9f92d7271f70c47067cc3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/script.md @@ -0,0 +1,38 @@ +## Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> + - <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> + + +<a name="api_nan_compile_script"></a> +### Nan::CompileScript() + +A wrapper around [`v8::Script::Compile()`](https://v8docs.nodesource.com/io.js-3.3/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b). + +Note that `Nan::BoundScript` is an alias for `v8::Script`. + +Signature: + +```c++ +Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript( + v8::Local<v8::String> s, + const v8::ScriptOrigin& origin); +Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s); +``` + + +<a name="api_nan_run_script"></a> +### Nan::RunScript() + +Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`. + +Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script) +Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script) +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/string_bytes.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/string_bytes.md new file mode 100644 index 0000000000000000000000000000000000000000..7c1bd3250476b6b16a29ff684a3a7f86de26a7f9 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/string_bytes.md @@ -0,0 +1,62 @@ +## Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> + - <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a> + - <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> + - <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> + + +<a name="api_nan_encoding"></a> +### Nan::Encoding + +An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node. + +Definition: + +```c++ +enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER } +``` + + +<a name="api_nan_encode"></a> +### Nan::Encode() + +A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::Encode(const void *buf, + size_t len, + enum Nan::Encoding encoding = BINARY); +``` + + +<a name="api_nan_decode_bytes"></a> +### Nan::DecodeBytes() + +A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val, + enum Nan::Encoding encoding = BINARY); +``` + + +<a name="api_nan_decode_write"></a> +### Nan::DecodeWrite() + +A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +ssize_t Nan::DecodeWrite(char *buf, + size_t len, + v8::Local<v8::Value> val, + enum Nan::Encoding encoding = BINARY); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_internals.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_internals.md new file mode 100644 index 0000000000000000000000000000000000000000..430c4353ffc18dd32fd859f362aeff047a2fd745 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_internals.md @@ -0,0 +1,199 @@ +## V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a> + - <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a> + - <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a> + - <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a> + - <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a> + - <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a> + - <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a> + - <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a> + - <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a> + - <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a> + - <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a> + - <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a> + - <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a> + - <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a> + - <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a> + + +<a name="api_nan_gc_callback"></a> +### NAN_GC_CALLBACK(callbackname) + +Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`. + +```c++ +static Nan::Persistent<Function> callback; + +NAN_GC_CALLBACK(gcPrologueCallback) { + v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() }; + Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv); +} + +NAN_METHOD(Hook) { + callback.Reset(To<Function>(args[0]).ToLocalChecked()); + Nan::AddGCPrologueCallback(gcPrologueCallback); + info.GetReturnValue().Set(info.Holder()); +} +``` + +<a name="api_nan_add_gc_epilogue_callback"></a> +### Nan::AddGCEpilogueCallback() + +Signature: + +```c++ +void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll) +``` + +Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a90d1860babc76059c62514b422f56960). + +<a name="api_nan_remove_gc_epilogue_callback"></a> +### Nan::RemoveGCEpilogueCallback() + +Signature: + +```c++ +void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) +``` + +Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a05c60859fd4b8e96bfcd451281ed6c7c). + +<a name="api_nan_add_gc_prologue_callback"></a> +### Nan::AddGCPrologueCallback() + +Signature: + +```c++ +void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback) +``` + +Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ab4b87b8f9f8e5bf95eba4009357e001f). + +<a name="api_nan_remove_gc_prologue_callback"></a> +### Nan::RemoveGCPrologueCallback() + +Signature: + +```c++ +void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) +``` + +Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a9f6c51932811593f81ff30b949124186). + +<a name="api_nan_get_heap_statistics"></a> +### Nan::GetHeapStatistics() + +Signature: + +```c++ +void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics) +``` + +Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34). + +<a name="api_nan_set_counter_function"></a> +### Nan::SetCounterFunction() + +Signature: + +```c++ +void Nan::SetCounterFunction(v8::CounterLookupCallback cb) +``` + +Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94). + +<a name="api_nan_set_create_histogram_function"></a> +### Nan::SetCreateHistogramFunction() + +Signature: + +```c++ +void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) +``` + +Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732). + +<a name="api_nan_set_add_histogram_sample_function"></a> +### Nan::SetAddHistogramSampleFunction() + +Signature: + +```c++ +void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) +``` + +Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea). + +<a name="api_nan_idle_notification"></a> +### Nan::IdleNotification() + +Signature: + +```c++ +void Nan::IdleNotification(v8::HeapStatistics *heap_statistics) +``` + +Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version. + +<a name="api_nan_low_memory_notification"></a> +### Nan::LowMemoryNotification() + +Signature: + +```c++ +void Nan::LowMemoryNotification() +``` + +Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f). + +<a name="api_nan_context_disposed_notification"></a> +### Nan::ContextDisposedNotification() + +Signature: + +```c++ +void Nan::ContextDisposedNotification() +``` + +Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b). + +<a name="api_nan_get_internal_field_pointer"></a> +### Nan::GetInternalFieldPointer() + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +Signature: + +```c++ +void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index) +``` + +Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8. + +<a name="api_nan_set_internal_field_pointer"></a> +### Nan::SetInternalFieldPointer() + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +Signature: + +```c++ +void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value) +``` + +Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b) depending on the version of V8. + +<a name="api_nan_adjust_external_memory"></a> +### Nan::AdjustExternalMemory() + +Signature: + +```c++ +int Nan::AdjustExternalMemory(int bytesChange) +``` + +Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_misc.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_misc.md new file mode 100644 index 0000000000000000000000000000000000000000..8aa6653f271f06417d7ad785109ca79faa58f3d4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/doc/v8_misc.md @@ -0,0 +1,85 @@ +## Miscellaneous V8 Helpers + + - <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> + - <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> + - <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> + - <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> + - <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> + + +<a name="api_nan_utf8_string"></a> +### Nan::Utf8String + +Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object. + +An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/io.js-3.3/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8. + +Definition: + +```c++ +class Nan::Utf8String { + public: + Nan::Utf8String(v8::Local<v8::Value> from); + + int length() const; + + char* operator*(); + const char* operator*() const; +}; +``` + +<a name="api_nan_get_current_context"></a> +### Nan::GetCurrentContext() + +A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Context> Nan::GetCurrentContext() +``` + +<a name="api_nan_set_isolate_data"></a> +### Nan::SetIsolateData() + +A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36). + +Signature: + +```c++ +void Nan::SetIsolateData(v8::Isolate *isolate, T *data) +``` + + +<a name="api_nan_get_isolate_data"></a> +### Nan::GetIsolateData() + +A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257). + +Signature: + +```c++ +T *Nan::GetIsolateData(v8::Isolate *isolate) +``` + +<a name="api_nan_typedarray_contents"></a> +### Nan::TypedArrayContents<T> + +A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail. + +Note that you must store a reference to the `array` object while you are accessing its contents. + +Definition: + +```c++ +template<typename T> +class Nan::TypedArrayContents { + public: + TypedArrayContents(v8::Local<Value> array); + + size_t length() const; + + T* const operator*(); + const T* const operator*() const; +}; +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/include_dirs.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/include_dirs.js new file mode 100644 index 0000000000000000000000000000000000000000..4f1dfb41667b9b86b4db9bb2255eaef5ab1b9ab6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/include_dirs.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan.h new file mode 100644 index 0000000000000000000000000000000000000000..29f084e7695467fda8f1d60f65c476f5fdb8adec --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan.h @@ -0,0 +1,2761 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors: + * - Rod Vagg <https://github.com/rvagg> + * - Benjamin Byholm <https://github.com/kkoopa> + * - Trevor Norris <https://github.com/trevnorris> + * - Nathan Rajlich <https://github.com/TooTallNate> + * - Brett Lawson <https://github.com/brett19> + * - Ben Noordhuis <https://github.com/bnoordhuis> + * - David Siegel <https://github.com/agnat> + * - Michael Ira Krufky <https://github.com/mkrufky> + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + * + * Version 2.10.0: current Node 9.8.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1 + * + * See https://github.com/nodejs/nan for the latest update to this file + **********************************************************************************/ + +#ifndef NAN_H_ +#define NAN_H_ + +#include <node_version.h> + +#define NODE_0_10_MODULE_VERSION 11 +#define NODE_0_12_MODULE_VERSION 14 +#define ATOM_0_21_MODULE_VERSION 41 +#define IOJS_1_0_MODULE_VERSION 42 +#define IOJS_1_1_MODULE_VERSION 43 +#define IOJS_2_0_MODULE_VERSION 44 +#define IOJS_3_0_MODULE_VERSION 45 +#define NODE_4_0_MODULE_VERSION 46 +#define NODE_5_0_MODULE_VERSION 47 +#define NODE_6_0_MODULE_VERSION 48 +#define NODE_7_0_MODULE_VERSION 51 +#define NODE_8_0_MODULE_VERSION 57 +#define NODE_9_0_MODULE_VERSION 59 + +#ifdef _MSC_VER +# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800) +#else +# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L) +#endif + +#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11 +# error This version of node/NAN/v8 requires a C++11 compiler +#endif + +#include <uv.h> +#include <node.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <algorithm> +#include <cstring> +#include <climits> +#include <cstdlib> +#include <utility> +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include <queue> +# include <string> +# include <vector> +# pragma warning( pop ) +#else +# include <queue> +# include <string> +# include <vector> +#endif + +// uv helpers +#ifdef UV_VERSION_MAJOR +# ifndef UV_VERSION_PATCH +# define UV_VERSION_PATCH 0 +# endif +# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ + (UV_VERSION_MINOR << 8) | \ + (UV_VERSION_PATCH)) +#else +# define NAUV_UVVERSION 0x000b00 +#endif + +#if NAUV_UVVERSION < 0x000b0b +# ifdef WIN32 +# include <windows.h> +# else +# include <pthread.h> +# endif +#endif + +namespace Nan { + +#define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0. + +#if defined(__GNUC__) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __declspec(deprecated) +#else +# define NAN_DEPRECATED +#endif + +#if NAN_HAS_CPLUSPLUS_11 +# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; +# define NAN_DISALLOW_MOVE(CLASS) \ + CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \ + void operator=(CLASS&&) = delete; +#else +# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&); +# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&); +# define NAN_DISALLOW_MOVE(CLASS) +#endif + +#define NAN_DISALLOW_ASSIGN_COPY(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_COPY(CLASS) + +#define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define NAN_DISALLOW_COPY_MOVE(CLASS) \ + NAN_DISALLOW_COPY(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_COPY(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define TYPE_CHECK(T, S) \ + while (false) { \ + *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \ + } + +//=== RegistrationFunction ===================================================== + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE; +#else + typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE; +#endif + +#define NAN_MODULE_INIT(name) \ + void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) + +//=== CallbackInfo ============================================================= + +#include "nan_callbacks.h" // NOLINT(build/include) + +//============================================================================== + +#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) +typedef v8::Script UnboundScript; +typedef v8::Script BoundScript; +#else +typedef v8::UnboundScript UnboundScript; +typedef v8::Script BoundScript; +#endif + +#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) +typedef v8::String::ExternalAsciiStringResource + ExternalOneByteStringResource; +#else +typedef v8::String::ExternalOneByteStringResource + ExternalOneByteStringResource; +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) +template<typename T> +class NonCopyablePersistentTraits : + public v8::NonCopyablePersistentTraits<T> {}; +template<typename T> +class CopyablePersistentTraits : + public v8::CopyablePersistentTraits<T> {}; + +template<typename T> +class PersistentBase : + public v8::PersistentBase<T> {}; + +template<typename T, typename M = v8::NonCopyablePersistentTraits<T> > +class Persistent; +#else +template<typename T> class NonCopyablePersistentTraits; +template<typename T> class PersistentBase; +template<typename T, typename P> class WeakCallbackData; +template<typename T, typename M = NonCopyablePersistentTraits<T> > +class Persistent; +#endif // NODE_MODULE_VERSION + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# include "nan_maybe_43_inl.h" // NOLINT(build/include) +#else +# include "nan_maybe_pre_43_inl.h" // NOLINT(build/include) +#endif + +#include "nan_converters.h" // NOLINT(build/include) +#include "nan_new.h" // NOLINT(build/include) + +#if NAUV_UVVERSION < 0x000b17 +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async, int) +#else +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async) +#endif + +#if NAUV_UVVERSION >= 0x000b0b + +typedef uv_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t *key) { + return uv_key_create(key); +} + +inline void nauv_key_delete(nauv_key_t *key) { + uv_key_delete(key); +} + +inline void* nauv_key_get(nauv_key_t *key) { + return uv_key_get(key); +} + +inline void nauv_key_set(nauv_key_t *key, void *value) { + uv_key_set(key, value); +} + +#else + +/* Implement thread local storage for older versions of libuv. + * This is essentially a backport of libuv commit 5d2434bf + * written by Ben Noordhuis, adjusted for names and inline. + */ + +#ifndef WIN32 + +typedef pthread_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + return -pthread_key_create(key, NULL); +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (pthread_key_delete(*key)) + abort(); +} + +inline void* nauv_key_get(nauv_key_t* key) { + return pthread_getspecific(*key); +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (pthread_setspecific(*key, value)) + abort(); +} + +#else + +typedef struct { + DWORD tls_index; +} nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + key->tls_index = TlsAlloc(); + if (key->tls_index == TLS_OUT_OF_INDEXES) + return UV_ENOMEM; + return 0; +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (TlsFree(key->tls_index) == FALSE) + abort(); + key->tls_index = TLS_OUT_OF_INDEXES; +} + +inline void* nauv_key_get(nauv_key_t* key) { + void* value = TlsGetValue(key->tls_index); + if (value == NULL) + if (GetLastError() != ERROR_SUCCESS) + abort(); + return value; +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (TlsSetValue(key->tls_index, value) == FALSE) + abort(); +} + +#endif +#endif + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template<typename T> +v8::Local<T> New(v8::Handle<T>); +#endif + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + typedef v8::WeakCallbackType WeakCallbackType; +#else +struct WeakCallbackType { + enum E {kParameter, kInternalFields}; + E type; + WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit) + inline bool operator==(E other) { return other == this->type; } + inline bool operator!=(E other) { return !operator==(other); } +}; +#endif + +template<typename P> class WeakCallbackInfo; + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# include "nan_persistent_12_inl.h" // NOLINT(build/include) +#else +# include "nan_persistent_pre_12_inl.h" // NOLINT(build/include) +#endif + +namespace imp { + static const size_t kMaxLength = 0x3fffffff; + // v8::String::REPLACE_INVALID_UTF8 was introduced + // in node.js v0.10.29 and v0.8.27. +#if NODE_MAJOR_VERSION > 0 || \ + NODE_MINOR_VERSION > 10 || \ + NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \ + NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27 + static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8; +#else + static const unsigned kReplaceInvalidUtf8 = 0; +#endif +} // end of namespace imp + +//=== HandleScope ============================================================== + +class HandleScope { + v8::HandleScope scope; + + public: +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + inline HandleScope() : scope(v8::Isolate::GetCurrent()) {} + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); + } +#else + inline HandleScope() : scope() {} + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(); + } +#endif + + private: + // Make it hard to create heap-allocated or illegal handle scopes by + // disallowing certain operations. + HandleScope(const HandleScope &); + void operator=(const HandleScope &); + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } +}; + +class EscapableHandleScope { + public: +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {} + + inline static int NumberOfHandles() { + return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); + } + + template<typename T> + inline v8::Local<T> Escape(v8::Local<T> value) { + return scope.Escape(value); + } + + private: + v8::EscapableHandleScope scope; +#else + inline EscapableHandleScope() : scope() {} + + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(); + } + + template<typename T> + inline v8::Local<T> Escape(v8::Local<T> value) { + return scope.Close(value); + } + + private: + v8::HandleScope scope; +#endif + + private: + // Make it hard to create heap-allocated or illegal handle scopes by + // disallowing certain operations. + EscapableHandleScope(const EscapableHandleScope &); + void operator=(const EscapableHandleScope &); + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } +}; + +//=== TryCatch ================================================================= + +class TryCatch { + v8::TryCatch try_catch_; + friend void FatalException(const TryCatch&); + + public: +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {} +#endif + + inline bool HasCaught() const { return try_catch_.HasCaught(); } + + inline bool CanContinue() const { return try_catch_.CanContinue(); } + + inline v8::Local<v8::Value> ReThrow() { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + return New(try_catch_.ReThrow()); +#else + return try_catch_.ReThrow(); +#endif + } + + inline v8::Local<v8::Value> Exception() const { + return try_catch_.Exception(); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline v8::MaybeLocal<v8::Value> StackTrace() const { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } +#else + inline MaybeLocal<v8::Value> StackTrace() const { + return try_catch_.StackTrace(); + } +#endif + + inline v8::Local<v8::Message> Message() const { + return try_catch_.Message(); + } + + inline void Reset() { try_catch_.Reset(); } + + inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); } + + inline void SetCaptureMessage(bool value) { + try_catch_.SetCaptureMessage(value); + } +}; + +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); + +// === AsyncResource =========================================================== + +class AsyncResource { + public: + AsyncResource( + v8::Local<v8::String> name + , v8::Local<v8::Object> resource = New<v8::Object>()) { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + + if (resource.IsEmpty()) { + resource = New<v8::Object>(); + } + + context = node::EmitAsyncInit(isolate, resource, name); +#endif + } + + AsyncResource( + const char* name + , v8::Local<v8::Object> resource = New<v8::Object>()) { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + + if (resource.IsEmpty()) { + resource = New<v8::Object>(); + } + + v8::Local<v8::String> name_string = + New<v8::String>(name).ToLocalChecked(); + context = node::EmitAsyncInit(isolate, resource, name_string); +#endif + } + + ~AsyncResource() { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::EmitAsyncDestroy(isolate, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, func, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, symbol, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, method, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv, context); +#endif + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource) +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + node::async_context context; +#endif +}; + +//============ ================================================================= + +/* node 0.12 */ +#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION + inline + void SetCounterFunction(v8::CounterLookupCallback cb) { + v8::Isolate::GetCurrent()->SetCounterFunction(cb); + } + + inline + void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); + } + + inline + void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline bool IdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotificationDeadline( + idle_time_in_ms * 0.001); + } +# else + inline bool IdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); + } +#endif + + inline void LowMemoryNotification() { + v8::Isolate::GetCurrent()->LowMemoryNotification(); + } + + inline void ContextDisposedNotification() { + v8::Isolate::GetCurrent()->ContextDisposedNotification(); + } +#else + inline + void SetCounterFunction(v8::CounterLookupCallback cb) { + v8::V8::SetCounterFunction(cb); + } + + inline + void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::V8::SetCreateHistogramFunction(cb); + } + + inline + void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::V8::SetAddHistogramSampleFunction(cb); + } + + inline bool IdleNotification(int idle_time_in_ms) { + return v8::V8::IdleNotification(idle_time_in_ms); + } + + inline void LowMemoryNotification() { + v8::V8::LowMemoryNotification(); + } + + inline void ContextDisposedNotification() { + v8::V8::ContextDisposedNotification(); + } +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12 + inline v8::Local<v8::Primitive> Undefined() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent()))); +# else + return v8::Undefined(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Primitive> Null() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent()))); +# else + return v8::Null(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Boolean> True() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::True(v8::Isolate::GetCurrent()))); +# else + return v8::True(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Boolean> False() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::False(v8::Isolate::GetCurrent()))); +# else + return v8::False(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::String> EmptyString() { + return v8::String::Empty(v8::Isolate::GetCurrent()); + } + + inline int AdjustExternalMemory(int bc) { + return static_cast<int>( + v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , const char *name + , v8::Local<v8::Data> value) { + templ->Set(v8::Isolate::GetCurrent(), name, value); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + inline v8::Local<v8::Context> GetCurrentContext() { + return v8::Isolate::GetCurrent()->GetCurrentContext(); + } + + inline void* GetInternalFieldPointer( + v8::Local<v8::Object> object + , int index) { + return object->GetAlignedPointerFromInternalField(index); + } + + inline void SetInternalFieldPointer( + v8::Local<v8::Object> object + , int index + , void* value) { + object->SetAlignedPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) + +#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION + typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback; + typedef v8::Isolate::GCPrologueCallback GCPrologueCallback; +#else + typedef v8::Isolate::GCCallback GCEpilogueCallback; + typedef v8::Isolate::GCCallback GCPrologueCallback; +#endif + + inline void AddGCEpilogueCallback( + GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); + } + + inline void RemoveGCEpilogueCallback( + GCEpilogueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); + } + + inline void AddGCPrologueCallback( + GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); + } + + inline void RemoveGCPrologueCallback( + GCPrologueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); + } + + inline void GetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); + } + +# define X(NAME) \ + inline v8::Local<v8::Value> NAME(const char *msg) { \ + EscapableHandleScope scope; \ + return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \ + return v8::Exception::NAME(msg); \ + } \ + \ + inline void Throw ## NAME(const char *msg) { \ + HandleScope scope; \ + v8::Isolate::GetCurrent()->ThrowException( \ + v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline void Throw ## NAME(v8::Local<v8::String> msg) { \ + HandleScope scope; \ + v8::Isolate::GetCurrent()->ThrowException( \ + v8::Exception::NAME(msg)); \ + } + + X(Error) + X(RangeError) + X(ReferenceError) + X(SyntaxError) + X(TypeError) + +# undef X + + inline void ThrowError(v8::Local<v8::Value> error) { + v8::Isolate::GetCurrent()->ThrowException(error); + } + + inline MaybeLocal<v8::Object> NewBuffer( + char *data + , size_t length +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + , node::Buffer::FreeCallback callback +#else + , node::smalloc::FreeCallback callback +#endif + , void *hint + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(length <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New( + v8::Isolate::GetCurrent(), data, length, callback, hint); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback, + hint); +#endif + } + + inline MaybeLocal<v8::Object> CopyBuffer( + const char *data + , uint32_t size + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::Copy( + v8::Isolate::GetCurrent(), data, size); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New( + v8::Isolate::GetCurrent(), size); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), size); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer( + char* data + , uint32_t size + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); +#else + return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); +#endif + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::NewStringType::kNormal, length); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source source(s, origin); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) + .FromMaybe(v8::Local<BoundScript>())); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source source(s); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) + .FromMaybe(v8::Local<BoundScript>())); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<UnboundScript> script + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(script->BindToCurrentContext() + ->Run(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<BoundScript> script + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(script->Run(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } +#else + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<UnboundScript> script + ) { + EscapableHandleScope scope; + return scope.Escape(script->BindToCurrentContext()->Run()); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<BoundScript> script + ) { + return script->Run(); + } +#endif + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, func, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, symbol, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, method, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + inline void FatalException(const TryCatch& try_catch) { + node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_); + } + + inline v8::Local<v8::Value> ErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall, + message, path); + } + + NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return ErrnoException(errorno, syscall, message, path); + } + + template<typename T> + inline void SetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(0, data); + } + + template<typename T> + inline T *GetIsolateData( + v8::Isolate *isolate + ) { + return static_cast<T*>(isolate->GetData(0)); + } + +class Utf8String { + public: + inline explicit Utf8String(v8::Local<v8::Value> from) : + length_(0), str_(str_st_) { + HandleScope scope; + if (!from.IsEmpty()) { + v8::Local<v8::String> string = from->ToString(); + if (!string.IsEmpty()) { + size_t len = 3 * string->Length() + 1; + assert(len <= INT_MAX); + if (len > sizeof (str_st_)) { + str_ = static_cast<char*>(malloc(len)); + assert(str_ != 0); + } + const int flags = + v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; + length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags); + str_[length_] = '\0'; + } + } + } + + inline int length() const { + return length_; + } + + inline char* operator*() { return str_; } + inline const char* operator*() const { return str_; } + + inline ~Utf8String() { + if (str_ != str_st_) { + free(str_); + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) + + int length_; + char *str_; + char str_st_[1024]; +}; + +#else // Node 0.8 and 0.10 + inline v8::Local<v8::Primitive> Undefined() { + EscapableHandleScope scope; + return scope.Escape(New(v8::Undefined())); + } + + inline v8::Local<v8::Primitive> Null() { + EscapableHandleScope scope; + return scope.Escape(New(v8::Null())); + } + + inline v8::Local<v8::Boolean> True() { + EscapableHandleScope scope; + return scope.Escape(New(v8::True())); + } + + inline v8::Local<v8::Boolean> False() { + EscapableHandleScope scope; + return scope.Escape(New(v8::False())); + } + + inline v8::Local<v8::String> EmptyString() { + return v8::String::Empty(); + } + + inline int AdjustExternalMemory(int bc) { + return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , const char *name + , v8::Local<v8::Data> value) { + templ->Set(name, value); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + inline v8::Local<v8::Context> GetCurrentContext() { + return v8::Context::GetCurrent(); + } + + inline void* GetInternalFieldPointer( + v8::Local<v8::Object> object + , int index) { + return object->GetPointerFromInternalField(index); + } + + inline void SetInternalFieldPointer( + v8::Local<v8::Object> object + , int index + , void* value) { + object->SetPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::GCType type, v8::GCCallbackFlags flags) + + inline void AddGCEpilogueCallback( + v8::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); + } + inline void RemoveGCEpilogueCallback( + v8::GCEpilogueCallback callback) { + v8::V8::RemoveGCEpilogueCallback(callback); + } + inline void AddGCPrologueCallback( + v8::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCPrologueCallback(callback, gc_type_filter); + } + inline void RemoveGCPrologueCallback( + v8::GCPrologueCallback callback) { + v8::V8::RemoveGCPrologueCallback(callback); + } + inline void GetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::V8::GetHeapStatistics(heap_statistics); + } + +# define X(NAME) \ + inline v8::Local<v8::Value> NAME(const char *msg) { \ + EscapableHandleScope scope; \ + return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \ + return v8::Exception::NAME(msg); \ + } \ + \ + inline void Throw ## NAME(const char *msg) { \ + HandleScope scope; \ + v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + void Throw ## NAME(v8::Local<v8::String> errmsg) { \ + HandleScope scope; \ + v8::ThrowException(v8::Exception::NAME(errmsg)); \ + } + + X(Error) + X(RangeError) + X(ReferenceError) + X(SyntaxError) + X(TypeError) + +# undef X + + inline void ThrowError(v8::Local<v8::Value> error) { + v8::ThrowException(error); + } + + inline MaybeLocal<v8::Object> NewBuffer( + char *data + , size_t length + , node::Buffer::free_callback callback + , void *hint + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(length <= imp::kMaxLength && "too large buffer"); + return scope.Escape( + New(node::Buffer::New(data, length, callback, hint)->handle_)); + } + + inline MaybeLocal<v8::Object> CopyBuffer( + const char *data + , uint32_t size + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return scope.Escape(New(node::Buffer::New(data, size)->handle_)); +#else + return scope.Escape( + New(node::Buffer::New(const_cast<char *>(data), size)->handle_)); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + assert(size <= imp::kMaxLength && "too large buffer"); + return scope.Escape(New(node::Buffer::New(size)->handle_)); + } + + inline void FreeData(char *data, void *hint) { + (void) hint; // unused + delete[] data; + } + + inline MaybeLocal<v8::Object> NewBuffer( + char* data + , uint32_t size + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); + return scope.Escape( + New(node::Buffer::New(data, size, FreeData, NULL)->handle_)); + } + +namespace imp { +inline void +widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) { + size_t len = static_cast<size_t>(l); + if (l < 0) { + len = strlen(reinterpret_cast<const char*>(s)); + } + assert(len <= INT_MAX && "string too long"); + ws->resize(len); + std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use) +} +} // end of namespace imp + + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use) + imp::widenString(&wideString, value, length); + return v8::String::New(wideString.data(), + static_cast<int>(wideString.size())); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin)); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + return v8::Script::Compile(s); + } + + inline + MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) { + return script->Run(); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, func, argc, argv))); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, symbol, argc, argv))); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, method, argc, argv))); + } + + inline void FatalException(const TryCatch& try_catch) { + node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_)); + } + + inline v8::Local<v8::Value> ErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return node::ErrnoException(errorno, syscall, message, path); + } + + NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return ErrnoException(errorno, syscall, message, path); + } + + + template<typename T> + inline void SetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(data); + } + + template<typename T> + inline T *GetIsolateData( + v8::Isolate *isolate + ) { + return static_cast<T*>(isolate->GetData()); + } + +class Utf8String { + public: + inline explicit Utf8String(v8::Local<v8::Value> from) : + length_(0), str_(str_st_) { + v8::HandleScope scope; + if (!from.IsEmpty()) { + v8::Local<v8::String> string = from->ToString(); + if (!string.IsEmpty()) { + size_t len = 3 * string->Length() + 1; + assert(len <= INT_MAX); + if (len > sizeof (str_st_)) { + str_ = static_cast<char*>(malloc(len)); + assert(str_ != 0); + } + const int flags = + v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; + length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags); + str_[length_] = '\0'; + } + } + } + + inline int length() const { + return length_; + } + + inline char* operator*() { return str_; } + inline const char* operator*() const { return str_; } + + inline ~Utf8String() { + if (str_ != str_st_) { + free(str_); + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) + + int length_; + char *str_; + char str_st_[1024]; +}; + +#endif // NODE_MODULE_VERSION + +typedef void (*FreeCallback)(char *data, void *hint); + +typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE; +typedef void NAN_METHOD_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE; +typedef void NAN_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE; +typedef void NAN_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& + NAN_PROPERTY_GETTER_ARGS_TYPE; +typedef void NAN_PROPERTY_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& + NAN_PROPERTY_SETTER_ARGS_TYPE; +typedef void NAN_PROPERTY_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Array>& + NAN_PROPERTY_ENUMERATOR_ARGS_TYPE; +typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Boolean>& + NAN_PROPERTY_DELETER_ARGS_TYPE; +typedef void NAN_PROPERTY_DELETER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Integer>& + NAN_PROPERTY_QUERY_ARGS_TYPE; +typedef void NAN_PROPERTY_QUERY_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE; +typedef void NAN_INDEX_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE; +typedef void NAN_INDEX_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Array>& + NAN_INDEX_ENUMERATOR_ARGS_TYPE; +typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Boolean>& + NAN_INDEX_DELETER_ARGS_TYPE; +typedef void NAN_INDEX_DELETER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Integer>& + NAN_INDEX_QUERY_ARGS_TYPE; +typedef void NAN_INDEX_QUERY_RETURN_TYPE; + +#define NAN_METHOD(name) \ + Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info) +#define NAN_GETTER(name) \ + Nan::NAN_GETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_GETTER_ARGS_TYPE info) +#define NAN_SETTER(name) \ + Nan::NAN_SETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , v8::Local<v8::Value> value \ + , Nan::NAN_SETTER_ARGS_TYPE info) +#define NAN_PROPERTY_GETTER(name) \ + Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) +#define NAN_PROPERTY_SETTER(name) \ + Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , v8::Local<v8::Value> value \ + , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) +#define NAN_PROPERTY_ENUMERATOR(name) \ + Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \ + Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) +#define NAN_PROPERTY_DELETER(name) \ + Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info) +#define NAN_PROPERTY_QUERY(name) \ + Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info) +# define NAN_INDEX_GETTER(name) \ + Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_GETTER_ARGS_TYPE info) +#define NAN_INDEX_SETTER(name) \ + Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \ + uint32_t index \ + , v8::Local<v8::Value> value \ + , Nan::NAN_INDEX_SETTER_ARGS_TYPE info) +#define NAN_INDEX_ENUMERATOR(name) \ + Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \ + name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) +#define NAN_INDEX_DELETER(name) \ + Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_DELETER_ARGS_TYPE info) +#define NAN_INDEX_QUERY(name) \ + Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_QUERY_ARGS_TYPE info) + +class Callback { + public: + Callback() {} + + explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {} + + ~Callback() { + handle_.Reset(); + } + + bool operator==(const Callback &other) const { + return handle_ == other.handle_; + } + + bool operator!=(const Callback &other) const { + return !operator==(other); + } + + inline + v8::Local<v8::Function> operator*() const { return GetFunction(); } + + NAN_DEPRECATED inline v8::Local<v8::Value> operator()( + v8::Local<v8::Object> target + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:operator()"); + return Call_(isolate, target, argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return Call_(isolate, target, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + return Call_(target, argc, argv); +#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> operator()( + int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:operator()"); + return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), + argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>())); +# else + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + } + + inline MaybeLocal<v8::Value> operator()( + AsyncResource* resource + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { + return this->Call(argc, argv, resource); + } + + inline MaybeLocal<v8::Value> operator()( + AsyncResource* resource + , v8::Local<v8::Object> target + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { + return this->Call(target, argc, argv, resource); + } + + // TODO(kkoopa): remove + inline void SetFunction(const v8::Local<v8::Function> &fn) { + Reset(fn); + } + + inline void Reset(const v8::Local<v8::Function> &fn) { + handle_.Reset(fn); + } + + inline void Reset() { + handle_.Reset(); + } + + inline v8::Local<v8::Function> GetFunction() const { + return New(handle_); + } + + inline bool IsEmpty() const { + return handle_.IsEmpty(); + } + + // Deprecated: For async callbacks Use the versions that accept an + // AsyncResource. If this callback does not correspond to an async resource, + // that is, it is a synchronous function call on a non-empty JS stack, you + // should Nan::Call instead. + NAN_DEPRECATED inline v8::Local<v8::Value> + Call(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:Call"); + return Call_(isolate, target, argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return Call_(isolate, target, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + return Call_(target, argc, argv); +#endif + } + + // Deprecated: For async callbacks Use the versions that accept an + // AsyncResource. If this callback does not correspond to an async resource, + // that is, it is a synchronous function call on a non-empty JS stack, you + // should Nan::Call instead. + NAN_DEPRECATED inline v8::Local<v8::Value> + Call(int argc, v8::Local<v8::Value> argv[]) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:Call"); + return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv, + &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif + } + + inline MaybeLocal<v8::Value> + Call(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[] + , AsyncResource* resource) const { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv, resource); +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv); +#else + return Call_(target, argc, argv); +#endif + } + + inline MaybeLocal<v8::Value> + Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource); +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback) + Persistent<v8::Function> handle_; + +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + MaybeLocal<v8::Value> Call_(v8::Isolate *isolate + , v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[] + , AsyncResource* resource) const { + EscapableHandleScope scope; + v8::Local<v8::Function> func = New(handle_); + auto maybe = resource->runInAsyncScope(target, func, argc, argv); + v8::Local<v8::Value> local; + if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>(); + return scope.Escape(local); + } +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Local<v8::Value> Call_(v8::Isolate *isolate + , v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { + EscapableHandleScope scope; + + v8::Local<v8::Function> callback = New(handle_); +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + return scope.Escape(New(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + ))); +# else + return scope.Escape(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + )); +# endif + } +#else + v8::Local<v8::Value> Call_(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { + EscapableHandleScope scope; + + v8::Local<v8::Function> callback = New(handle_); + return scope.Escape(New(node::MakeCallback( + target + , callback + , argc + , argv + ))); + } +#endif +}; + +inline MaybeLocal<v8::Value> Call( + const Nan::Callback& callback + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + return Call(*callback, recv, argc, argv); +} + +inline MaybeLocal<v8::Value> Call( + const Nan::Callback& callback + , int argc + , v8::Local<v8::Value> argv[]) { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +#else + EscapableHandleScope scope; + return scope.Escape( + Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +#endif +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::String> symbol + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + EscapableHandleScope scope; + v8::Local<v8::Value> fn_v = + Get(recv, symbol).FromMaybe(v8::Local<v8::Value>()); + if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>(); + v8::Local<v8::Function> fn = fn_v.As<v8::Function>(); + return scope.Escape( + Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> Call( + const char* method + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + EscapableHandleScope scope; + v8::Local<v8::String> method_string = + New<v8::String>(method).ToLocalChecked(); + return scope.Escape( + Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>())); +} + +/* abstract */ class AsyncWorker { + public: + explicit AsyncWorker(Callback *callback_, + const char* resource_name = "nan:AsyncWorker") + : callback(callback_), errmsg_(NULL) { + request.data = this; + + HandleScope scope; + v8::Local<v8::Object> obj = New<v8::Object>(); + persistentHandle.Reset(obj); + async_resource = new AsyncResource(resource_name, obj); + } + + virtual ~AsyncWorker() { + HandleScope scope; + + if (!persistentHandle.IsEmpty()) + persistentHandle.Reset(); + delete callback; + delete[] errmsg_; + delete async_resource; + } + + virtual void WorkComplete() { + HandleScope scope; + + if (errmsg_ == NULL) + HandleOKCallback(); + else + HandleErrorCallback(); + delete callback; + callback = NULL; + } + + inline void SaveToPersistent( + const char *key, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(New(key).ToLocalChecked(), value); + } + + inline void SaveToPersistent( + const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(key, value); + } + + inline void SaveToPersistent( + uint32_t index, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(index, value); + } + + inline v8::Local<v8::Value> GetFromPersistent(const char *key) const { + EscapableHandleScope scope; + return scope.Escape( + New(persistentHandle)->Get(New(key).ToLocalChecked())); + } + + inline v8::Local<v8::Value> + GetFromPersistent(const v8::Local<v8::String> &key) const { + EscapableHandleScope scope; + return scope.Escape(New(persistentHandle)->Get(key)); + } + + inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const { + EscapableHandleScope scope; + return scope.Escape(New(persistentHandle)->Get(index)); + } + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy() { + delete this; + } + + protected: + Persistent<v8::Object> persistentHandle; + Callback *callback; + AsyncResource *async_resource; + + virtual void HandleOKCallback() { + HandleScope scope; + + callback->Call(0, NULL, async_resource); + } + + virtual void HandleErrorCallback() { + HandleScope scope; + + v8::Local<v8::Value> argv[] = { + v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked()) + }; + callback->Call(1, argv, async_resource); + } + + void SetErrorMessage(const char *msg) { + delete[] errmsg_; + + size_t size = strlen(msg) + 1; + errmsg_ = new char[size]; + memcpy(errmsg_, msg, size); + } + + const char* ErrorMessage() const { + return errmsg_; + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker) + char *errmsg_; +}; + +/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker { + public: + explicit AsyncBareProgressWorkerBase( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressWorkerBase") + : AsyncWorker(callback_, resource_name) { + uv_async_init( + uv_default_loop() + , &async + , AsyncProgress_ + ); + async.data = this; + } + + virtual ~AsyncBareProgressWorkerBase() { + } + + virtual void WorkProgress() = 0; + + virtual void Destroy() { + uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_); + } + + private: + inline static NAUV_WORK_CB(AsyncProgress_) { + AsyncBareProgressWorkerBase *worker = + static_cast<AsyncBareProgressWorkerBase*>(async->data); + worker->WorkProgress(); + } + + inline static void AsyncClose_(uv_handle_t* handle) { + AsyncBareProgressWorkerBase *worker = + static_cast<AsyncBareProgressWorkerBase*>(handle->data); + delete worker; + } + + protected: + uv_async_t async; +}; + +template<class T> +/* abstract */ +class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase { + public: + explicit AsyncBareProgressWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressWorker") + : AsyncBareProgressWorkerBase(callback_, resource_name) { + } + + virtual ~AsyncBareProgressWorker() { + } + + class ExecutionProgress { + friend class AsyncBareProgressWorker; + public: + void Signal() const { + uv_async_send(&that_->async); + } + + void Send(const T* data, size_t count) const { + that_->SendProgress_(data, count); + } + + private: + explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {} + NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) + AsyncBareProgressWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const T *data, size_t size) = 0; + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + virtual void SendProgress_(const T *data, size_t count) = 0; +}; + +template<class T> +/* abstract */ +class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> { + public: + explicit AsyncProgressWorkerBase( + Callback *callback_, + const char* resource_name = "nan:AsyncProgressWorkerBase") + : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL), + asyncsize_(0) { + uv_mutex_init(&async_lock); + } + + virtual ~AsyncProgressWorkerBase() { + uv_mutex_destroy(&async_lock); + + delete[] asyncdata_; + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + T *data = asyncdata_; + size_t size = asyncsize_; + asyncdata_ = NULL; + uv_mutex_unlock(&async_lock); + + // Don't send progress events after we've already completed. + if (this->callback) { + this->HandleProgressCallback(data, size); + } + delete[] data; + } + + private: + void SendProgress_(const T *data, size_t count) { + T *new_data = new T[count]; + { + T *it = new_data; + std::copy(data, data + count, it); + } + + uv_mutex_lock(&async_lock); + T *old_data = asyncdata_; + asyncdata_ = new_data; + asyncsize_ = count; + uv_mutex_unlock(&async_lock); + + delete[] old_data; + uv_async_send(&this->async); + } + + uv_mutex_t async_lock; + T *asyncdata_; + size_t asyncsize_; +}; + +// This ensures compatibility to the previous un-templated AsyncProgressWorker +// class definition. +typedef AsyncProgressWorkerBase<char> AsyncProgressWorker; + +template<class T> +/* abstract */ +class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase { + public: + explicit AsyncBareProgressQueueWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressQueueWorker") + : AsyncBareProgressWorkerBase(callback_, resource_name) { + } + + virtual ~AsyncBareProgressQueueWorker() { + } + + class ExecutionProgress { + friend class AsyncBareProgressQueueWorker; + public: + void Send(const T* data, size_t count) const { + that_->SendProgress_(data, count); + } + + private: + explicit ExecutionProgress(AsyncBareProgressQueueWorker *that) + : that_(that) {} + NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) + AsyncBareProgressQueueWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const T *data, size_t size) = 0; + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + virtual void SendProgress_(const T *data, size_t count) = 0; +}; + +template<class T> +/* abstract */ +class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> { + public: + explicit AsyncProgressQueueWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncProgressQueueWorker") + : AsyncBareProgressQueueWorker<T>(callback_) { + uv_mutex_init(&async_lock); + } + + virtual ~AsyncProgressQueueWorker() { + uv_mutex_lock(&async_lock); + + while (!asyncdata_.empty()) { + std::pair<T*, size_t> &datapair = asyncdata_.front(); + T *data = datapair.first; + + asyncdata_.pop(); + + delete[] data; + } + + uv_mutex_unlock(&async_lock); + uv_mutex_destroy(&async_lock); + } + + void WorkComplete() { + WorkProgress(); + AsyncWorker::WorkComplete(); + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + + while (!asyncdata_.empty()) { + std::pair<T*, size_t> &datapair = asyncdata_.front(); + + T *data = datapair.first; + size_t size = datapair.second; + + asyncdata_.pop(); + uv_mutex_unlock(&async_lock); + + // Don't send progress events after we've already completed. + if (this->callback) { + this->HandleProgressCallback(data, size); + } + + delete[] data; + + uv_mutex_lock(&async_lock); + } + + uv_mutex_unlock(&async_lock); + } + + private: + void SendProgress_(const T *data, size_t count) { + T *new_data = new T[count]; + { + T *it = new_data; + std::copy(data, data + count, it); + } + + uv_mutex_lock(&async_lock); + asyncdata_.push(std::pair<T*, size_t>(new_data, count)); + uv_mutex_unlock(&async_lock); + + uv_async_send(&this->async); + } + + uv_mutex_t async_lock; + std::queue<std::pair<T*, size_t> > asyncdata_; +}; + +inline void AsyncExecute (uv_work_t* req) { + AsyncWorker *worker = static_cast<AsyncWorker*>(req->data); + worker->Execute(); +} + +inline void AsyncExecuteComplete (uv_work_t* req) { + AsyncWorker* worker = static_cast<AsyncWorker*>(req->data); + worker->WorkComplete(); + worker->Destroy(); +} + +inline void AsyncQueueWorker (AsyncWorker* worker) { + uv_queue_work( + uv_default_loop() + , &worker->request + , AsyncExecute + , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete) + ); +} + +namespace imp { + +inline +ExternalOneByteStringResource const* +GetExternalResource(v8::Local<v8::String> str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->GetExternalAsciiStringResource(); +#else + return str->GetExternalOneByteStringResource(); +#endif +} + +inline +bool +IsExternal(v8::Local<v8::String> str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->IsExternalAscii(); +#else + return str->IsExternalOneByte(); +#endif +} + +} // end of namespace imp + +enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; + +#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION +# include "nan_string_bytes.h" // NOLINT(build/include) +#endif + +inline v8::Local<v8::Value> Encode( + const void *buf, size_t len, enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::encoding node_enc = static_cast<node::encoding>(encoding); + + if (encoding == UCS2) { + return node::Encode( + isolate + , reinterpret_cast<const uint16_t *>(buf) + , len / 2); + } else { + return node::Encode( + isolate + , reinterpret_cast<const char *>(buf) + , len + , node_enc); + } +#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::Encode( + v8::Isolate::GetCurrent() + , buf, len + , static_cast<node::encoding>(encoding)); +#else +# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return node::Encode(buf, len, static_cast<node::encoding>(encoding)); +# else + return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding); +# endif +#endif +} + +inline ssize_t DecodeBytes( + v8::Local<v8::Value> val, enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeBytes( + v8::Isolate::GetCurrent() + , val + , static_cast<node::encoding>(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == BUFFER) { + return node::DecodeBytes(val, node::BINARY); + } +# endif + return node::DecodeBytes(val, static_cast<node::encoding>(encoding)); +#endif +} + +inline ssize_t DecodeWrite( + char *buf + , size_t len + , v8::Local<v8::Value> val + , enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeWrite( + v8::Isolate::GetCurrent() + , buf + , len + , val + , static_cast<node::encoding>(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == BUFFER) { + return node::DecodeWrite(buf, len, val, node::BINARY); + } +# endif + return node::DecodeWrite( + buf + , len + , val + , static_cast<node::encoding>(encoding)); +#endif +} + +inline void SetPrototypeTemplate( + v8::Local<v8::FunctionTemplate> templ + , const char *name + , v8::Local<v8::Data> value +) { + HandleScope scope; + SetTemplate(templ->PrototypeTemplate(), name, value); +} + +inline void SetPrototypeTemplate( + v8::Local<v8::FunctionTemplate> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes +) { + HandleScope scope; + SetTemplate(templ->PrototypeTemplate(), name, value, attributes); +} + +inline void SetInstanceTemplate( + v8::Local<v8::FunctionTemplate> templ + , const char *name + , v8::Local<v8::Data> value +) { + HandleScope scope; + SetTemplate(templ->InstanceTemplate(), name, value); +} + +inline void SetInstanceTemplate( + v8::Local<v8::FunctionTemplate> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes +) { + HandleScope scope; + SetTemplate(templ->InstanceTemplate(), name, value, attributes); +} + +namespace imp { + +// Note(@agnat): Helper to distinguish different receiver types. The first +// version deals with receivers derived from v8::Template. The second version +// handles everything else. The final argument only serves as discriminator and +// is unused. +template <typename T> +inline +void +SetMethodAux(T recv, + v8::Local<v8::String> name, + v8::Local<v8::FunctionTemplate> tpl, + v8::Template *) { + recv->Set(name, tpl); +} + +template <typename T> +inline +void +SetMethodAux(T recv, + v8::Local<v8::String> name, + v8::Local<v8::FunctionTemplate> tpl, + ...) { + recv->Set(name, GetFunction(tpl).ToLocalChecked()); +} + +} // end of namespace imp + +template <typename T, template <typename> class HandleType> +inline void SetMethod( + HandleType<T> recv + , const char *name + , FunctionCallback callback) { + HandleScope scope; + v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback); + v8::Local<v8::String> fn_name = New(name).ToLocalChecked(); + t->SetClassName(fn_name); + // Note(@agnat): Pass an empty T* as discriminator. See note on + // SetMethodAux(...) above + imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0)); +} + +inline void SetPrototypeMethod( + v8::Local<v8::FunctionTemplate> recv + , const char* name, FunctionCallback callback) { + HandleScope scope; + v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>( + callback + , v8::Local<v8::Value>() + , New<v8::Signature>(recv)); + v8::Local<v8::String> fn_name = New(name).ToLocalChecked(); + recv->PrototypeTemplate()->Set(fn_name, t); + t->SetClassName(fn_name); +} + +//=== Accessors and Such ======================================================= + +inline void SetAccessor( + v8::Local<v8::ObjectTemplate> tpl + , v8::Local<v8::String> name + , GetterCallback getter + , SetterCallback setter = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::AccessControl settings = v8::DEFAULT + , v8::PropertyAttribute attribute = v8::None + , imp::Sig signature = imp::Sig()) { + HandleScope scope; + + imp::NativeGetter getter_ = + imp::GetterCallbackWrapper; + imp::NativeSetter setter_ = + setter ? imp::SetterCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kAccessorFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter != 0) { + obj->SetInternalField( + imp::kSetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetAccessor( + name + , getter_ + , setter_ + , obj + , settings + , attribute + , signature); +} + +inline bool SetAccessor( + v8::Local<v8::Object> obj + , v8::Local<v8::String> name + , GetterCallback getter + , SetterCallback setter = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::AccessControl settings = v8::DEFAULT + , v8::PropertyAttribute attribute = v8::None) { + HandleScope scope; + + imp::NativeGetter getter_ = + imp::GetterCallbackWrapper; + imp::NativeSetter setter_ = + setter ? imp::SetterCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kAccessorFieldCount); + v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked(); + + dataobj->SetInternalField( + imp::kGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (!data.IsEmpty()) { + dataobj->SetInternalField(imp::kDataIndex, data); + } + + if (setter) { + dataobj->SetInternalField( + imp::kSetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + return obj->SetAccessor( + GetCurrentContext() + , name + , getter_ + , setter_ + , dataobj + , settings + , attribute).FromMaybe(false); +#else + return obj->SetAccessor( + name + , getter_ + , setter_ + , dataobj + , settings + , attribute); +#endif +} + +inline void SetNamedPropertyHandler( + v8::Local<v8::ObjectTemplate> tpl + , PropertyGetterCallback getter + , PropertySetterCallback setter = 0 + , PropertyQueryCallback query = 0 + , PropertyDeleterCallback deleter = 0 + , PropertyEnumeratorCallback enumerator = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + imp::NativePropertyGetter getter_ = + imp::PropertyGetterCallbackWrapper; + imp::NativePropertySetter setter_ = + setter ? imp::PropertySetterCallbackWrapper : 0; + imp::NativePropertyQuery query_ = + query ? imp::PropertyQueryCallbackWrapper : 0; + imp::NativePropertyDeleter *deleter_ = + deleter ? imp::PropertyDeleterCallbackWrapper : 0; + imp::NativePropertyEnumerator enumerator_ = + enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kPropertyFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + obj->SetInternalField( + imp::kPropertyGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter) { + obj->SetInternalField( + imp::kPropertySetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (query) { + obj->SetInternalField( + imp::kPropertyQueryIndex + , New<v8::External>(reinterpret_cast<void *>(query))); + } + + if (deleter) { + obj->SetInternalField( + imp::kPropertyDeleterIndex + , New<v8::External>(reinterpret_cast<void *>(deleter))); + } + + if (enumerator) { + obj->SetInternalField( + imp::kPropertyEnumeratorIndex + , New<v8::External>(reinterpret_cast<void *>(enumerator))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + tpl->SetHandler(v8::NamedPropertyHandlerConfiguration( + getter_, setter_, query_, deleter_, enumerator_, obj)); +#else + tpl->SetNamedPropertyHandler( + getter_ + , setter_ + , query_ + , deleter_ + , enumerator_ + , obj); +#endif +} + +inline void SetIndexedPropertyHandler( + v8::Local<v8::ObjectTemplate> tpl + , IndexGetterCallback getter + , IndexSetterCallback setter = 0 + , IndexQueryCallback query = 0 + , IndexDeleterCallback deleter = 0 + , IndexEnumeratorCallback enumerator = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + imp::NativeIndexGetter getter_ = + imp::IndexGetterCallbackWrapper; + imp::NativeIndexSetter setter_ = + setter ? imp::IndexSetterCallbackWrapper : 0; + imp::NativeIndexQuery query_ = + query ? imp::IndexQueryCallbackWrapper : 0; + imp::NativeIndexDeleter deleter_ = + deleter ? imp::IndexDeleterCallbackWrapper : 0; + imp::NativeIndexEnumerator enumerator_ = + enumerator ? imp::IndexEnumeratorCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + obj->SetInternalField( + imp::kIndexPropertyGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter) { + obj->SetInternalField( + imp::kIndexPropertySetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (query) { + obj->SetInternalField( + imp::kIndexPropertyQueryIndex + , New<v8::External>(reinterpret_cast<void *>(query))); + } + + if (deleter) { + obj->SetInternalField( + imp::kIndexPropertyDeleterIndex + , New<v8::External>(reinterpret_cast<void *>(deleter))); + } + + if (enumerator) { + obj->SetInternalField( + imp::kIndexPropertyEnumeratorIndex + , New<v8::External>(reinterpret_cast<void *>(enumerator))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration( + getter_, setter_, query_, deleter_, enumerator_, obj)); +#else + tpl->SetIndexedPropertyHandler( + getter_ + , setter_ + , query_ + , deleter_ + , enumerator_ + , obj); +#endif +} + +inline void SetCallHandler( + v8::Local<v8::FunctionTemplate> tpl + , FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , New<v8::External>(reinterpret_cast<void *>(callback))); + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj); +} + + +inline void SetCallAsFunctionHandler( + v8::Local<v8::ObjectTemplate> tpl, + FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , New<v8::External>(reinterpret_cast<void *>(callback))); + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj); +} + +//=== Weak Persistent Handling ================================================= + +#include "nan_weak.h" // NOLINT(build/include) + +//=== ObjectWrap =============================================================== + +#include "nan_object_wrap.h" // NOLINT(build/include) + +//=== HiddenValue/Private ====================================================== + +#include "nan_private.h" // NOLINT(build/include) + +//=== Export ================================================================== + +inline +void +Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name, + FunctionCallback f) { + HandleScope scope; + + Set(target, New<v8::String>(name).ToLocalChecked(), + GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked()); +} + +//=== Tap Reverse Binding ===================================================== + +struct Tap { + explicit Tap(v8::Local<v8::Value> t) : t_() { + HandleScope scope; + + t_.Reset(To<v8::Object>(t).ToLocalChecked()); + } + + ~Tap() { t_.Reset(); } // not sure if neccessary + + inline void plan(int i) { + HandleScope scope; + v8::Local<v8::Value> arg = New(i); + Call("plan", New(t_), 1, &arg); + } + + inline void ok(bool isOk, const char *msg = NULL) { + HandleScope scope; + v8::Local<v8::Value> args[2]; + args[0] = New(isOk); + if (msg) args[1] = New(msg).ToLocalChecked(); + Call("ok", New(t_), msg ? 2 : 1, args); + } + + inline void pass(const char * msg = NULL) { + HandleScope scope; + v8::Local<v8::Value> hmsg; + if (msg) hmsg = New(msg).ToLocalChecked(); + Call("pass", New(t_), msg ? 1 : 0, &hmsg); + } + + inline void end() { + HandleScope scope; + Call("end", New(t_), 0, NULL); + } + + private: + Persistent<v8::Object> t_; +}; + +#define NAN_STRINGIZE2(x) #x +#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) +#define NAN_TEST_EXPRESSION(expression) \ + ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression + +#define NAN_EXPORT(target, function) Export(target, #function, function) + +#undef TYPE_CHECK + +//=== Generic Maybefication =================================================== + +namespace imp { + +template <typename T> struct Maybefier; + +template <typename T> struct Maybefier<v8::Local<T> > { + inline static MaybeLocal<T> convert(v8::Local<T> v) { + return v; + } +}; + +template <typename T> struct Maybefier<MaybeLocal<T> > { + inline static MaybeLocal<T> convert(MaybeLocal<T> v) { + return v; + } +}; + +} // end of namespace imp + +template <typename T, template <typename> class MaybeMaybe> +inline MaybeLocal<T> +MakeMaybe(MaybeMaybe<T> v) { + return imp::Maybefier<MaybeMaybe<T> >::convert(v); +} + +//=== TypedArrayContents ======================================================= + +#include "nan_typedarray_contents.h" // NOLINT(build/include) + +//=== JSON ===================================================================== + +#include "nan_json.h" // NOLINT(build/include) + +} // end of namespace Nan + +#endif // NAN_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks.h new file mode 100644 index 0000000000000000000000000000000000000000..53ede846ac9a865a737218dabbbd48305d3d6b63 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks.h @@ -0,0 +1,88 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_H_ +#define NAN_CALLBACKS_H_ + +template<typename T> class FunctionCallbackInfo; +template<typename T> class PropertyCallbackInfo; +template<typename T> class Global; + +typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&); +typedef void(*GetterCallback) + (v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&); +typedef void(*SetterCallback)( + v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<void>&); +typedef void(*PropertyGetterCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*PropertySetterCallback)( + v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*PropertyEnumeratorCallback) + (const PropertyCallbackInfo<v8::Array>&); +typedef void(*PropertyDeleterCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Boolean>&); +typedef void(*PropertyQueryCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Integer>&); +typedef void(*IndexGetterCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*IndexSetterCallback)( + uint32_t, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*IndexEnumeratorCallback) + (const PropertyCallbackInfo<v8::Array>&); +typedef void(*IndexDeleterCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Boolean>&); +typedef void(*IndexQueryCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Integer>&); + +namespace imp { +typedef v8::Local<v8::AccessorSignature> Sig; + +static const int kDataIndex = 0; + +static const int kFunctionIndex = 1; +static const int kFunctionFieldCount = 2; + +static const int kGetterIndex = 1; +static const int kSetterIndex = 2; +static const int kAccessorFieldCount = 3; + +static const int kPropertyGetterIndex = 1; +static const int kPropertySetterIndex = 2; +static const int kPropertyEnumeratorIndex = 3; +static const int kPropertyDeleterIndex = 4; +static const int kPropertyQueryIndex = 5; +static const int kPropertyFieldCount = 6; + +static const int kIndexPropertyGetterIndex = 1; +static const int kIndexPropertySetterIndex = 2; +static const int kIndexPropertyEnumeratorIndex = 3; +static const int kIndexPropertyDeleterIndex = 4; +static const int kIndexPropertyQueryIndex = 5; +static const int kIndexPropertyFieldCount = 6; + +} // end of namespace imp + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# include "nan_callbacks_12_inl.h" // NOLINT(build/include) +#else +# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include) +#endif + +#endif // NAN_CALLBACKS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..d3df79aaf0e21a6f175966e55b523823b704ba29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_12_inl.h @@ -0,0 +1,512 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_12_INL_H_ +#define NAN_CALLBACKS_12_INL_H_ + +template<typename T> +class ReturnValue { + v8::ReturnValue<T> value_; + + public: + template <class S> + explicit inline ReturnValue(const v8::ReturnValue<S> &value) : + value_(value) {} + template <class S> + explicit inline ReturnValue(const ReturnValue<S>& that) + : value_(that.value_) { + TYPE_CHECK(T, S); + } + + // Handle setters + template <typename S> inline void Set(const v8::Local<S> &handle) { + TYPE_CHECK(T, S); + value_.Set(handle); + } + + template <typename S> inline void Set(const Global<S> &handle) { + TYPE_CHECK(T, S); +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \ + (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \ + defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8)))) + value_.Set(handle); +#else + value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle)); + const_cast<Global<S> &>(handle).Reset(); +#endif + } + + // Fast primitive setters + inline void Set(bool value) { + TYPE_CHECK(T, v8::Boolean); + value_.Set(value); + } + + inline void Set(double i) { + TYPE_CHECK(T, v8::Number); + value_.Set(i); + } + + inline void Set(int32_t i) { + TYPE_CHECK(T, v8::Integer); + value_.Set(i); + } + + inline void Set(uint32_t i) { + TYPE_CHECK(T, v8::Integer); + value_.Set(i); + } + + // Fast JS primitive setters + inline void SetNull() { + TYPE_CHECK(T, v8::Primitive); + value_.SetNull(); + } + + inline void SetUndefined() { + TYPE_CHECK(T, v8::Primitive); + value_.SetUndefined(); + } + + inline void SetEmptyString() { + TYPE_CHECK(T, v8::String); + value_.SetEmptyString(); + } + + // Convenience getter for isolate + inline v8::Isolate *GetIsolate() const { + return value_.GetIsolate(); + } + + // Pointer setter: Uncompilable to prevent inadvertent misuse. + template<typename S> + inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } +}; + +template<typename T> +class FunctionCallbackInfo { + const v8::FunctionCallbackInfo<T> &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline FunctionCallbackInfo( + const v8::FunctionCallbackInfo<T> &info + , v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(info_.GetReturnValue()); + } + + inline v8::Local<v8::Function> Callee() const { return info_.Callee(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + inline bool IsConstructCall() const { return info_.IsConstructCall(); } + inline int Length() const { return info_.Length(); } + inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); } + + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kCalleeIndex = 5; + static const int kContextSaveIndex = 6; + static const int kArgsLength = 7; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) +}; + +template<typename T> +class PropertyCallbackInfo { + const v8::PropertyCallbackInfo<T> &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline PropertyCallbackInfo( + const v8::PropertyCallbackInfo<T> &info + , const v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(info_.GetReturnValue()); + } + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kThisIndex = 5; + static const int kArgsLength = 6; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo) +}; + +namespace imp { +static +void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + FunctionCallback callback = reinterpret_cast<FunctionCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value())); + FunctionCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + callback(cbinfo); +} + +typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &); + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +static +void GetterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativeGetter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void SetterCallbackWrapper( + v8::Local<v8::Name> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<void> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property.As<v8::String>(), value, cbinfo); +} + +typedef void (*NativeSetter)( + v8::Local<v8::Name> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<void> &); +#else +static +void GetterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativeGetter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void SetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<void> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativeSetter)( + v8::Local<v8::String> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<void> &); +#endif + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +static +void PropertyGetterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativePropertyGetter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertySetterCallbackWrapper( + v8::Local<v8::Name> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), value, cbinfo); +} + +typedef void (*NativePropertySetter)( + v8::Local<v8::Name> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertyEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativePropertyEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void PropertyDeleterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (NativePropertyDeleter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void PropertyQueryCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativePropertyQuery) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &); +#else +static +void PropertyGetterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativePropertyGetter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertySetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativePropertySetter)( + v8::Local<v8::String> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertyEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativePropertyEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void PropertyDeleterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (NativePropertyDeleter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void PropertyQueryCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativePropertyQuery) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &); +#endif + +static +void IndexGetterCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexGetter) + (uint32_t, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void IndexSetterCallbackWrapper( + uint32_t index + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertySetterIndex) + .As<v8::External>()->Value())); + callback(index, value, cbinfo); +} + +typedef void (*NativeIndexSetter)( + uint32_t + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void IndexEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField( + kIndexPropertyEnumeratorIndex).As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativeIndexEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void IndexDeleterCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexDeleter) + (uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void IndexQueryCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexQuery) + (uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &); +} // end of namespace imp + +#endif // NAN_CALLBACKS_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..c9ba4993205ec4feed387870b8f33f05e0789f1a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h @@ -0,0 +1,520 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_PRE_12_INL_H_ +#define NAN_CALLBACKS_PRE_12_INL_H_ + +namespace imp { +template<typename T> class ReturnValueImp; +} // end of namespace imp + +template<typename T> +class ReturnValue { + v8::Isolate *isolate_; + v8::Persistent<T> *value_; + friend class imp::ReturnValueImp<T>; + + public: + template <class S> + explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) : + isolate_(isolate), value_(p) {} + template <class S> + explicit inline ReturnValue(const ReturnValue<S>& that) + : isolate_(that.isolate_), value_(that.value_) { + TYPE_CHECK(T, S); + } + + // Handle setters + template <typename S> inline void Set(const v8::Local<S> &handle) { + TYPE_CHECK(T, S); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(handle); + } + + template <typename S> inline void Set(const Global<S> &handle) { + TYPE_CHECK(T, S); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(handle.persistent); + const_cast<Global<S> &>(handle).Reset(); + } + + // Fast primitive setters + inline void Set(bool value) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Boolean); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Boolean::New(value)); + } + + inline void Set(double i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Number); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Number::New(i)); + } + + inline void Set(int32_t i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Integer); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Int32::New(i)); + } + + inline void Set(uint32_t i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Integer); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i)); + } + + // Fast JS primitive setters + inline void SetNull() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Primitive); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Null()); + } + + inline void SetUndefined() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Primitive); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Undefined()); + } + + inline void SetEmptyString() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::String); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::String::Empty()); + } + + // Convenience getter for isolate + inline v8::Isolate *GetIsolate() const { + return isolate_; + } + + // Pointer setter: Uncompilable to prevent inadvertent misuse. + template<typename S> + inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } +}; + +template<typename T> +class FunctionCallbackInfo { + const v8::Arguments &args_; + v8::Local<v8::Value> data_; + ReturnValue<T> return_value_; + v8::Persistent<T> retval_; + + public: + explicit inline FunctionCallbackInfo( + const v8::Arguments &args + , v8::Local<v8::Value> data) : + args_(args) + , data_(data) + , return_value_(args.GetIsolate(), &retval_) + , retval_(v8::Persistent<T>::New(v8::Undefined())) {} + + inline ~FunctionCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(return_value_); + } + + inline v8::Local<v8::Function> Callee() const { return args_.Callee(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> Holder() const { return args_.Holder(); } + inline bool IsConstructCall() const { return args_.IsConstructCall(); } + inline int Length() const { return args_.Length(); } + inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; } + inline v8::Local<v8::Object> This() const { return args_.This(); } + inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); } + + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kCalleeIndex = 5; + static const int kContextSaveIndex = 6; + static const int kArgsLength = 7; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) +}; + +template<typename T> +class PropertyCallbackInfoBase { + const v8::AccessorInfo &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline PropertyCallbackInfoBase( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kThisIndex = 5; + static const int kArgsLength = 6; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase) +}; + +template<typename T> +class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> { + ReturnValue<T> return_value_; + v8::Persistent<T> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<T>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<T>::New(v8::Undefined())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<T> GetReturnValue() const { return return_value_; } +}; + +template<> +class PropertyCallbackInfo<v8::Array> : + public PropertyCallbackInfoBase<v8::Array> { + ReturnValue<v8::Array> return_value_; + v8::Persistent<v8::Array> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Array>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Array> GetReturnValue() const { + return return_value_; + } +}; + +template<> +class PropertyCallbackInfo<v8::Boolean> : + public PropertyCallbackInfoBase<v8::Boolean> { + ReturnValue<v8::Boolean> return_value_; + v8::Persistent<v8::Boolean> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Boolean>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Boolean> GetReturnValue() const { + return return_value_; + } +}; + +template<> +class PropertyCallbackInfo<v8::Integer> : + public PropertyCallbackInfoBase<v8::Integer> { + ReturnValue<v8::Integer> return_value_; + v8::Persistent<v8::Integer> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Integer>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Integer> GetReturnValue() const { + return return_value_; + } +}; + +namespace imp { +template<typename T> +class ReturnValueImp : public ReturnValue<T> { + public: + explicit ReturnValueImp(ReturnValue<T> that) : + ReturnValue<T>(that) {} + inline v8::Handle<T> Value() { + return *ReturnValue<T>::value_; + } +}; + +static +v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) { + v8::Local<v8::Object> obj = args.Data().As<v8::Object>(); + FunctionCallback callback = reinterpret_cast<FunctionCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value())); + FunctionCallbackInfo<v8::Value> + cbinfo(args, obj->GetInternalField(kDataIndex)); + callback(cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &); + +static +v8::Handle<v8::Value> GetterCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeGetter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +void SetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativeSetter) + (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> PropertyGetterCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativePropertyGetter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> PropertySetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property, value, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativePropertySetter) + (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper( + const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); + return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Array> (*NativePropertyEnumerator) + (const v8::AccessorInfo &); + +static +v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper( + v8::Local<v8::String> property + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Boolean> (NativePropertyDeleter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Integer> PropertyQueryCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Integer> (*NativePropertyQuery) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> IndexGetterCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeIndexGetter) + (uint32_t, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> IndexSetterCallbackWrapper( + uint32_t index + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertySetterIndex) + .As<v8::External>()->Value())); + callback(index, value, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeIndexSetter) + (uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper( + const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); + return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Array> (*NativeIndexEnumerator) + (const v8::AccessorInfo &); + +static +v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter) + (uint32_t, const v8::AccessorInfo &); + +static +v8::Handle<v8::Integer> IndexQueryCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Integer> (*NativeIndexQuery) + (uint32_t, const v8::AccessorInfo &); +} // end of namespace imp + +#endif // NAN_CALLBACKS_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b327294644045c2c7611d11e1cd83dd3ccab70 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters.h @@ -0,0 +1,72 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_H_ +#define NAN_CONVERTERS_H_ + +namespace imp { +template<typename T> struct ToFactoryBase { + typedef MaybeLocal<T> return_t; +}; +template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; }; + +template<typename T> struct ToFactory; + +template<> +struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> { + static inline return_t convert(v8::Local<v8::Value> val) { + if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>(); + return MaybeLocal<v8::Function>(val.As<v8::Function>()); + } +}; + +#define X(TYPE) \ + template<> \ + struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \ + static inline return_t convert(v8::Local<v8::Value> val); \ + }; + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE) \ + template<> \ + struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \ + static inline return_t convert(v8::Local<v8::Value> val); \ + }; + +X(bool) +X(double) +X(int64_t) +X(uint32_t) +X(int32_t) + +#undef X +} // end of namespace imp + +template<typename T> +inline +typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) { + return imp::ToFactory<T>::convert(val); +} + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# include "nan_converters_43_inl.h" +#else +# include "nan_converters_pre_43_inl.h" +#endif + +#endif // NAN_CONVERTERS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..742f543279f0e8d30ba54c3538266c161b86cd0f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_43_inl.h @@ -0,0 +1,48 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_43_INL_H_ +#define NAN_CONVERTERS_43_INL_H_ + +#define X(TYPE) \ +imp::ToFactory<v8::TYPE>::return_t \ +imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ + v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ + v8::EscapableHandleScope scope(isolate); \ + return scope.Escape( \ + val->To ## TYPE(isolate->GetCurrentContext()) \ + .FromMaybe(v8::Local<v8::TYPE>())); \ +} + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE, NAME) \ +imp::ToFactory<TYPE>::return_t \ +imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ + v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ + v8::HandleScope scope(isolate); \ + return val->NAME ## Value(isolate->GetCurrentContext()); \ +} + +X(bool, Boolean) +X(double, Number) +X(int64_t, Integer) +X(uint32_t, Uint32) +X(int32_t, Int32) + +#undef X + +#endif // NAN_CONVERTERS_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_pre_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_pre_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..ae0518aa33d0851cd08dfd8a3bb321508e02b64a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_converters_pre_43_inl.h @@ -0,0 +1,42 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_PRE_43_INL_H_ +#define NAN_CONVERTERS_PRE_43_INL_H_ + +#define X(TYPE) \ +imp::ToFactory<v8::TYPE>::return_t \ +imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ + return val->To ## TYPE(); \ +} + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE, NAME) \ +imp::ToFactory<TYPE>::return_t \ +imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ + return Just(val->NAME ## Value()); \ +} + +X(bool, Boolean) +X(double, Number) +X(int64_t, Integer) +X(uint32_t, Uint32) +X(int32_t, Int32) + +#undef X + +#endif // NAN_CONVERTERS_PRE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_define_own_property_helper.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_define_own_property_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..d710ef2293d93746e87b671e7c5e8577784f9e27 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_define_own_property_helper.h @@ -0,0 +1,29 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_ +#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_ + +namespace imp { + +inline Maybe<bool> DefineOwnPropertyHelper( + v8::PropertyAttribute current + , v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + return !(current & v8::DontDelete) || // configurable OR + (!(current & v8::ReadOnly) && // writable AND + !((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO + ? Just<bool>(obj->ForceSet(key, value, attribs)) + : Nothing<bool>(); +} + +} // end of namespace imp + +#endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..baacb3801782f2ecdf40f570cece4e6412c3c256 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_12_inl.h @@ -0,0 +1,399 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_12_INL_H_ +#define NAN_IMPLEMENTATION_12_INL_H_ +//============================================================================== +// node v0.11 implementation +//============================================================================== + +namespace imp { + +//=== Array ==================================================================== + +Factory<v8::Array>::return_t +Factory<v8::Array>::New() { + return v8::Array::New(v8::Isolate::GetCurrent()); +} + +Factory<v8::Array>::return_t +Factory<v8::Array>::New(int length) { + return v8::Array::New(v8::Isolate::GetCurrent(), length); +} + +//=== Boolean ================================================================== + +Factory<v8::Boolean>::return_t +Factory<v8::Boolean>::New(bool value) { + return v8::Boolean::New(v8::Isolate::GetCurrent(), value); +} + +//=== Boolean Object =========================================================== + +Factory<v8::BooleanObject>::return_t +Factory<v8::BooleanObject>::New(bool value) { +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + return v8::BooleanObject::New( + v8::Isolate::GetCurrent(), value).As<v8::BooleanObject>(); +#else + return v8::BooleanObject::New(value).As<v8::BooleanObject>(); +#endif +} + +//=== Context ================================================================== + +Factory<v8::Context>::return_t +Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions + , v8::Local<v8::ObjectTemplate> tmpl + , v8::Local<v8::Value> obj) { + return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); +} + +//=== Date ===================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value) + .FromMaybe(v8::Local<v8::Value>()).As<v8::Date>()); +} +#else +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>(); +} +#endif + +//=== External ================================================================= + +Factory<v8::External>::return_t +Factory<v8::External>::New(void * value) { + return v8::External::New(v8::Isolate::GetCurrent(), value); +} + +//=== Function ================================================================= + +Factory<v8::Function>::return_t +Factory<v8::Function>::New( FunctionCallback callback + , v8::Local<v8::Value> data) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(isolate, reinterpret_cast<void *>(callback))); + + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + return scope.Escape(v8::Function::New( isolate + , imp::FunctionCallbackWrapper + , obj)); +} + +//=== Function Template ======================================================== + +Factory<v8::FunctionTemplate>::return_t +Factory<v8::FunctionTemplate>::New( FunctionCallback callback + , v8::Local<v8::Value> data + , v8::Local<v8::Signature> signature) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + if (callback) { + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(isolate, reinterpret_cast<void *>(callback))); + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + return scope.Escape(v8::FunctionTemplate::New( isolate + , imp::FunctionCallbackWrapper + , obj + , signature)); + } else { + return v8::FunctionTemplate::New(isolate, 0, data, signature); + } +} + +//=== Number =================================================================== + +Factory<v8::Number>::return_t +Factory<v8::Number>::New(double value) { + return v8::Number::New(v8::Isolate::GetCurrent(), value); +} + +//=== Number Object ============================================================ + +Factory<v8::NumberObject>::return_t +Factory<v8::NumberObject>::New(double value) { + return v8::NumberObject::New( v8::Isolate::GetCurrent() + , value).As<v8::NumberObject>(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(int32_t value) { + return To<T>(T::New(v8::Isolate::GetCurrent(), value)); +} + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(uint32_t value) { + return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(int32_t value) { + return To<v8::Uint32>( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(uint32_t value) { + return To<v8::Uint32>( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +//=== Object =================================================================== + +Factory<v8::Object>::return_t +Factory<v8::Object>::New() { + return v8::Object::New(v8::Isolate::GetCurrent()); +} + +//=== Object Template ========================================================== + +Factory<v8::ObjectTemplate>::return_t +Factory<v8::ObjectTemplate>::New() { + return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); +} + +//=== RegExp =================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags) + .FromMaybe(v8::Local<v8::RegExp>())); +} +#else +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} +#endif + +//=== Script =================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source src(source); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) + .FromMaybe(v8::Local<v8::Script>())); +} + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source src(source, origin); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) + .FromMaybe(v8::Local<v8::Script>())); +} +#else +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} +#endif + +//=== Signature ================================================================ + +Factory<v8::Signature>::return_t +Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); +} + +//=== String =================================================================== + +Factory<v8::String>::return_t +Factory<v8::String>::New() { + return v8::String::Empty(v8::Isolate::GetCurrent()); +} + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::NewFromUtf8( + v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), + value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::NewStringType::kNormal, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(ExternalOneByteStringResource * value) { + return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value); +} +#else +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New( + std::string const& value) /* NOLINT(build/include_what_you_use) */ { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(), + v8::String::kNormalString, + static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(ExternalOneByteStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} +#endif + +//=== String Object ============================================================ + +Factory<v8::StringObject>::return_t +Factory<v8::StringObject>::New(v8::Local<v8::String> value) { + return v8::StringObject::New(value).As<v8::StringObject>(); +} + +//=== Unbound Script =========================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnboundScript( + v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnboundScript( + v8::Isolate::GetCurrent(), &src); +} +#else +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} +#endif + +} // end of namespace imp + +//=== Presistents and Handles ================================================== + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template <typename T> +inline v8::Local<T> New(v8::Handle<T> h) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), h); +} +#endif + +template <typename T, typename M> +inline v8::Local<T> New(v8::Persistent<T, M> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +template <typename T> +inline v8::Local<T> New(Global<T> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..1472421afa76883abdc6077d92b7c5d3b6000e77 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_implementation_pre_12_inl.h @@ -0,0 +1,263 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ +#define NAN_IMPLEMENTATION_PRE_12_INL_H_ + +//============================================================================== +// node v0.10 implementation +//============================================================================== + +namespace imp { + +//=== Array ==================================================================== + +Factory<v8::Array>::return_t +Factory<v8::Array>::New() { + return v8::Array::New(); +} + +Factory<v8::Array>::return_t +Factory<v8::Array>::New(int length) { + return v8::Array::New(length); +} + +//=== Boolean ================================================================== + +Factory<v8::Boolean>::return_t +Factory<v8::Boolean>::New(bool value) { + return v8::Boolean::New(value)->ToBoolean(); +} + +//=== Boolean Object =========================================================== + +Factory<v8::BooleanObject>::return_t +Factory<v8::BooleanObject>::New(bool value) { + return v8::BooleanObject::New(value).As<v8::BooleanObject>(); +} + +//=== Context ================================================================== + +Factory<v8::Context>::return_t +Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions + , v8::Local<v8::ObjectTemplate> tmpl + , v8::Local<v8::Value> obj) { + v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx); + ctx.Dispose(); + return lctx; +} + +//=== Date ===================================================================== + +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + return v8::Date::New(value).As<v8::Date>(); +} + +//=== External ================================================================= + +Factory<v8::External>::return_t +Factory<v8::External>::New(void * value) { + return v8::External::New(value); +} + +//=== Function ================================================================= + +Factory<v8::Function>::return_t +Factory<v8::Function>::New( FunctionCallback callback + , v8::Local<v8::Value> data) { + v8::HandleScope scope; + + return scope.Close(Factory<v8::FunctionTemplate>::New( + callback, data, v8::Local<v8::Signature>()) + ->GetFunction()); +} + + +//=== FunctionTemplate ========================================================= + +Factory<v8::FunctionTemplate>::return_t +Factory<v8::FunctionTemplate>::New( FunctionCallback callback + , v8::Local<v8::Value> data + , v8::Local<v8::Signature> signature) { + if (callback) { + v8::HandleScope scope; + + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = tpl->NewInstance(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(reinterpret_cast<void *>(callback))); + + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find + // a way. Have at it though... + return scope.Close( + v8::FunctionTemplate::New(imp::FunctionCallbackWrapper + , obj + , signature)); + } else { + return v8::FunctionTemplate::New(0, data, signature); + } +} + +//=== Number =================================================================== + +Factory<v8::Number>::return_t +Factory<v8::Number>::New(double value) { + return v8::Number::New(value); +} + +//=== Number Object ============================================================ + +Factory<v8::NumberObject>::return_t +Factory<v8::NumberObject>::New(double value) { + return v8::NumberObject::New(value).As<v8::NumberObject>(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(int32_t value) { + return To<T>(T::New(value)); +} + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(uint32_t value) { + return To<T>(T::NewFromUnsigned(value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(int32_t value) { + return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(uint32_t value) { + return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value)); +} + + +//=== Object =================================================================== + +Factory<v8::Object>::return_t +Factory<v8::Object>::New() { + return v8::Object::New(); +} + +//=== Object Template ========================================================== + +Factory<v8::ObjectTemplate>::return_t +Factory<v8::ObjectTemplate>::New() { + return v8::ObjectTemplate::New(); +} + +//=== RegExp =================================================================== + +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + return v8::Script::New(source); +} +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + return v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin)); +} + +//=== Signature ================================================================ + +Factory<v8::Signature>::return_t +Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) { + return v8::Signature::New(receiver); +} + +//=== String =================================================================== + +Factory<v8::String>::return_t +Factory<v8::String>::New() { + return v8::String::Empty(); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::New(value, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New( + std::string const& value) /* NOLINT(build/include_what_you_use) */ { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::New(value.data(), static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::New(value, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) { + return v8::String::NewExternal(value); +} + +//=== String Object ============================================================ + +Factory<v8::StringObject>::return_t +Factory<v8::StringObject>::New(v8::Local<v8::String> value) { + return v8::StringObject::New(value).As<v8::StringObject>(); +} + +} // end of namespace imp + +//=== Presistents and Handles ================================================== + +template <typename T> +inline v8::Local<T> New(v8::Handle<T> h) { + return v8::Local<T>::New(h); +} + +template <typename T> +inline v8::Local<T> New(v8::Persistent<T> const& p) { + return v8::Local<T>::New(p); +} + +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p) { + return v8::Local<T>::New(p.persistent); +} + +template <typename T> +inline v8::Local<T> New(Global<T> const& p) { + return v8::Local<T>::New(p.persistent); +} + +#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_json.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_json.h new file mode 100644 index 0000000000000000000000000000000000000000..33ac8ba69a082f5be23ce56d4c2d2cc078cd7646 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_json.h @@ -0,0 +1,166 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_JSON_H_ +#define NAN_JSON_H_ + +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION +#define NAN_JSON_H_NEED_PARSE 1 +#else +#define NAN_JSON_H_NEED_PARSE 0 +#endif // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + +#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION +#define NAN_JSON_H_NEED_STRINGIFY 0 +#else +#define NAN_JSON_H_NEED_STRINGIFY 1 +#endif // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION + +class JSON { + public: + JSON() { +#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY + Nan::HandleScope scope; + + Nan::MaybeLocal<v8::Value> maybe_global_json = Nan::Get( + Nan::GetCurrentContext()->Global(), + Nan::New("JSON").ToLocalChecked() + ); + + assert(!maybe_global_json.IsEmpty() && "global JSON is empty"); + v8::Local<v8::Value> val_global_json = maybe_global_json.ToLocalChecked(); + + assert(val_global_json->IsObject() && "global JSON is not an object"); + Nan::MaybeLocal<v8::Object> maybe_obj_global_json = + Nan::To<v8::Object>(val_global_json); + + assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty"); + v8::Local<v8::Object> global_json = maybe_obj_global_json.ToLocalChecked(); + +#if NAN_JSON_H_NEED_PARSE + Nan::MaybeLocal<v8::Value> maybe_parse_method = Nan::Get( + global_json, Nan::New("parse").ToLocalChecked() + ); + + assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty"); + v8::Local<v8::Value> parse_method = maybe_parse_method.ToLocalChecked(); + + assert(parse_method->IsFunction() && "JSON.parse is not a function"); + parse_cb_.Reset(parse_method.As<v8::Function>()); +#endif // NAN_JSON_H_NEED_PARSE + +#if NAN_JSON_H_NEED_STRINGIFY + Nan::MaybeLocal<v8::Value> maybe_stringify_method = Nan::Get( + global_json, Nan::New("stringify").ToLocalChecked() + ); + + assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty"); + v8::Local<v8::Value> stringify_method = + maybe_stringify_method.ToLocalChecked(); + + assert( + stringify_method->IsFunction() && "JSON.stringify is not a function" + ); + stringify_cb_.Reset(stringify_method.As<v8::Function>()); +#endif // NAN_JSON_H_NEED_STRINGIFY +#endif // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY + } + + inline + Nan::MaybeLocal<v8::Value> Parse(v8::Local<v8::String> json_string) { + Nan::EscapableHandleScope scope; +#if NAN_JSON_H_NEED_PARSE + return scope.Escape(parse(json_string)); +#else + Nan::MaybeLocal<v8::Value> result; +#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \ + NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION + result = v8::JSON::Parse(json_string); +#else +#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION + v8::Local<v8::Context> context_or_isolate = Nan::GetCurrentContext(); +#else + v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent(); +#endif // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION + result = v8::JSON::Parse(context_or_isolate, json_string); +#endif // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && + // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION + if (result.IsEmpty()) return v8::Local<v8::Value>(); + return scope.Escape(result.ToLocalChecked()); +#endif // NAN_JSON_H_NEED_PARSE + } + + inline + Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object) { + Nan::EscapableHandleScope scope; + Nan::MaybeLocal<v8::String> result = +#if NAN_JSON_H_NEED_STRINGIFY + Nan::To<v8::String>(stringify(json_object)); +#else + v8::JSON::Stringify(Nan::GetCurrentContext(), json_object); +#endif // NAN_JSON_H_NEED_STRINGIFY + if (result.IsEmpty()) return v8::Local<v8::String>(); + return scope.Escape(result.ToLocalChecked()); + } + + inline + Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object, + v8::Local<v8::String> gap) { + Nan::EscapableHandleScope scope; + Nan::MaybeLocal<v8::String> result = +#if NAN_JSON_H_NEED_STRINGIFY + Nan::To<v8::String>(stringify(json_object, gap)); +#else + v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap); +#endif // NAN_JSON_H_NEED_STRINGIFY + if (result.IsEmpty()) return v8::Local<v8::String>(); + return scope.Escape(result.ToLocalChecked()); + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON) +#if NAN_JSON_H_NEED_PARSE + Nan::Callback parse_cb_; +#endif // NAN_JSON_H_NEED_PARSE +#if NAN_JSON_H_NEED_STRINGIFY + Nan::Callback stringify_cb_; +#endif // NAN_JSON_H_NEED_STRINGIFY + +#if NAN_JSON_H_NEED_PARSE + inline v8::Local<v8::Value> parse(v8::Local<v8::Value> arg) { + assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty"); + AsyncResource resource("nan:JSON.parse"); + return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local<v8::Value>()); + } +#endif // NAN_JSON_H_NEED_PARSE + +#if NAN_JSON_H_NEED_STRINGIFY + inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg) { + assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); + AsyncResource resource("nan:JSON.stringify"); + return stringify_cb_.Call(1, &arg, &resource) + .FromMaybe(v8::Local<v8::Value>()); + } + + inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg, + v8::Local<v8::String> gap) { + assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); + + v8::Local<v8::Value> argv[] = { + arg, + Nan::Null(), + gap + }; + AsyncResource resource("nan:JSON.stringify"); + return stringify_cb_.Call(3, argv, &resource) + .FromMaybe(v8::Local<v8::Value>()); + } +#endif // NAN_JSON_H_NEED_STRINGIFY +}; + +#endif // NAN_JSON_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..91783da65aa9cdcf5dda96668966e6f1b0ce3fbb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_43_inl.h @@ -0,0 +1,369 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_MAYBE_43_INL_H_ +#define NAN_MAYBE_43_INL_H_ + +template<typename T> +using MaybeLocal = v8::MaybeLocal<T>; + +template<typename T> +using Maybe = v8::Maybe<T>; + +template<typename T> +inline Maybe<T> Nothing() { + return v8::Nothing<T>(); +} + +template<typename T> +inline Maybe<T> Just(const T& t) { + return v8::Just<T>(t); +} + +inline +MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(val->ToDetailString(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline +MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Uint32>())); +} + +inline +Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return a->Equals(isolate->GetCurrentContext(), b); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Object>())); +} + +inline +MaybeLocal<v8::Object> NewInstance( + v8::Local<v8::Function> h + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv) + .FromMaybe(v8::Local<v8::Object>())); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Object>())); +} + + +inline MaybeLocal<v8::Function> GetFunction( + v8::Local<v8::FunctionTemplate> t) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(t->GetFunction(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Function>())); +} + +inline Maybe<bool> Set( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key + , v8::Local<v8::Value> value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Set(isolate->GetCurrentContext(), key, value); +} + +inline Maybe<bool> Set( + v8::Local<v8::Object> obj + , uint32_t index + , v8::Local<v8::Value> value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Set(isolate->GetCurrentContext(), index, value); +} + +#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION +#include "nan_define_own_property_helper.h" // NOLINT(build/include) +#endif + +inline Maybe<bool> DefineOwnProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key + , v8::Local<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); +#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION + return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value, + attribs); +#else + Maybe<v8::PropertyAttribute> maybeCurrent = + obj->GetPropertyAttributes(isolate->GetCurrentContext(), key); + if (maybeCurrent.IsNothing()) { + return Nothing<bool>(); + } + v8::PropertyAttribute current = maybeCurrent.FromJust(); + return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); +#endif +} + +NAN_DEPRECATED inline Maybe<bool> ForceSet( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key + , v8::Local<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + return key->IsName() + ? obj->DefineOwnProperty(isolate->GetCurrentContext(), + key.As<v8::Name>(), value, attribs) + : Nothing<bool>(); +#else + return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs); +#endif +} + +inline MaybeLocal<v8::Value> Get( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->Get(isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline +MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->Get(isolate->GetCurrentContext(), index) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline v8::PropertyAttribute GetPropertyAttributes( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key) + .FromJust(); +} + +inline Maybe<bool> Has( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Has(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Has(isolate->GetCurrentContext(), index); +} + +inline Maybe<bool> Delete( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Delete(isolate->GetCurrentContext(), key); +} + +inline +Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Delete(isolate->GetCurrentContext(), index); +} + +inline +MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Array>())); +} + +inline +MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Array>())); +} + +inline Maybe<bool> SetPrototype( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> prototype) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->SetPrototype(isolate->GetCurrentContext(), prototype); +} + +inline MaybeLocal<v8::String> ObjectProtoToString( + v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline Maybe<bool> HasOwnProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasOwnProperty(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> HasRealNamedProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> HasRealIndexedProperty( + v8::Local<v8::Object> obj + , uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index); +} + +inline Maybe<bool> HasRealNamedCallbackProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key); +} + +inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain( + isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> GetRealNamedProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->GetRealNamedProperty(isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> CallAsFunction( + v8::Local<v8::Object> obj + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> CallAsConstructor( + v8::Local<v8::Object> obj + , int argc, v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline +MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetLineNumber(isolate->GetCurrentContext()); +} + +inline Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetStartColumn(isolate->GetCurrentContext()); +} + +inline Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetEndColumn(isolate->GetCurrentContext()); +} + +inline MaybeLocal<v8::Object> CloneElementAt( + v8::Local<v8::Array> array + , uint32_t index) { +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Value> elem; + v8::Local<v8::Object> obj; + if (!array->Get(context, index).ToLocal(&elem)) { + return scope.Escape(obj); + } + if (!elem->ToObject(context).ToLocal(&obj)) { + return scope.Escape(v8::Local<v8::Object>()); + } + return scope.Escape(obj->Clone()); +#else + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index) + .FromMaybe(v8::Local<v8::Object>())); +#endif +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::Function> fun + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +#endif // NAN_MAYBE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_pre_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_pre_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..3847296d5d22d69fa55b21a95033a89aea2802dc --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_maybe_pre_43_inl.h @@ -0,0 +1,316 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_MAYBE_PRE_43_INL_H_ +#define NAN_MAYBE_PRE_43_INL_H_ + +template<typename T> +class MaybeLocal { + public: + inline MaybeLocal() : val_(v8::Local<T>()) {} + + template<typename S> +# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION + inline + MaybeLocal(v8::Local<S> that) : val_(that) {} // NOLINT(runtime/explicit) +# else + inline + MaybeLocal(v8::Local<S> that) : // NOLINT(runtime/explicit) + val_(*reinterpret_cast<v8::Local<T>*>(&that)) {} +# endif + + inline bool IsEmpty() const { return val_.IsEmpty(); } + + template<typename S> + inline bool ToLocal(v8::Local<S> *out) const { + *out = val_; + return !IsEmpty(); + } + + inline v8::Local<T> ToLocalChecked() const { +#if defined(V8_ENABLE_CHECKS) + assert(!IsEmpty() && "ToLocalChecked is Empty"); +#endif // V8_ENABLE_CHECKS + return val_; + } + + template<typename S> + inline v8::Local<S> FromMaybe(v8::Local<S> default_value) const { + return IsEmpty() ? default_value : v8::Local<S>(val_); + } + + private: + v8::Local<T> val_; +}; + +template<typename T> +class Maybe { + public: + inline bool IsNothing() const { return !has_value_; } + inline bool IsJust() const { return has_value_; } + + inline T FromJust() const { +#if defined(V8_ENABLE_CHECKS) + assert(IsJust() && "FromJust is Nothing"); +#endif // V8_ENABLE_CHECKS + return value_; + } + + inline T FromMaybe(const T& default_value) const { + return has_value_ ? value_ : default_value; + } + + inline bool operator==(const Maybe &other) const { + return (IsJust() == other.IsJust()) && + (!IsJust() || FromJust() == other.FromJust()); + } + + inline bool operator!=(const Maybe &other) const { + return !operator==(other); + } + + private: + Maybe() : has_value_(false) {} + explicit Maybe(const T& t) : has_value_(true), value_(t) {} + bool has_value_; + T value_; + + template<typename U> + friend Maybe<U> Nothing(); + template<typename U> + friend Maybe<U> Just(const U& u); +}; + +template<typename T> +inline Maybe<T> Nothing() { + return Maybe<T>(); +} + +template<typename T> +inline Maybe<T> Just(const T& t) { + return Maybe<T>(t); +} + +inline +MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) { + return MaybeLocal<v8::String>(val->ToDetailString()); +} + +inline +MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) { + return MaybeLocal<v8::Uint32>(val->ToArrayIndex()); +} + +inline +Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) { + return Just<bool>(a->Equals(b)); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) { + return MaybeLocal<v8::Object>(h->NewInstance()); +} + +inline +MaybeLocal<v8::Object> NewInstance( + v8::Local<v8::Function> h + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Object>(h->NewInstance(argc, argv)); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) { + return MaybeLocal<v8::Object>(h->NewInstance()); +} + +inline +MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) { + return MaybeLocal<v8::Function>(t->GetFunction()); +} + +inline Maybe<bool> Set( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key + , v8::Handle<v8::Value> value) { + return Just<bool>(obj->Set(key, value)); +} + +inline Maybe<bool> Set( + v8::Handle<v8::Object> obj + , uint32_t index + , v8::Handle<v8::Value> value) { + return Just<bool>(obj->Set(index, value)); +} + +#include "nan_define_own_property_helper.h" // NOLINT(build/include) + +inline Maybe<bool> DefineOwnProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::PropertyAttribute current = obj->GetPropertyAttributes(key); + return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); +} + +NAN_DEPRECATED inline Maybe<bool> ForceSet( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + return Just<bool>(obj->ForceSet(key, value, attribs)); +} + +inline MaybeLocal<v8::Value> Get( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key) { + return MaybeLocal<v8::Value>(obj->Get(key)); +} + +inline MaybeLocal<v8::Value> Get( + v8::Handle<v8::Object> obj + , uint32_t index) { + return MaybeLocal<v8::Value>(obj->Get(index)); +} + +inline Maybe<v8::PropertyAttribute> GetPropertyAttributes( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key) { + return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key)); +} + +inline Maybe<bool> Has( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->Has(key)); +} + +inline Maybe<bool> Has( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->Has(index)); +} + +inline Maybe<bool> Delete( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->Delete(key)); +} + +inline Maybe<bool> Delete( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->Delete(index)); +} + +inline +MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::Array>(obj->GetPropertyNames()); +} + +inline +MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames()); +} + +inline Maybe<bool> SetPrototype( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> prototype) { + return Just<bool>(obj->SetPrototype(prototype)); +} + +inline MaybeLocal<v8::String> ObjectProtoToString( + v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::String>(obj->ObjectProtoToString()); +} + +inline Maybe<bool> HasOwnProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasOwnProperty(key)); +} + +inline Maybe<bool> HasRealNamedProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasRealNamedProperty(key)); +} + +inline Maybe<bool> HasRealIndexedProperty( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->HasRealIndexedProperty(index)); +} + +inline Maybe<bool> HasRealNamedCallbackProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasRealNamedCallbackProperty(key)); +} + +inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return MaybeLocal<v8::Value>( + obj->GetRealNamedPropertyInPrototypeChain(key)); +} + +inline MaybeLocal<v8::Value> GetRealNamedProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key)); +} + +inline MaybeLocal<v8::Value> CallAsFunction( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Object> recv + , int argc + , v8::Handle<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv)); +} + +inline MaybeLocal<v8::Value> CallAsConstructor( + v8::Handle<v8::Object> obj + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv)); +} + +inline +MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) { + return MaybeLocal<v8::String>(msg->GetSourceLine()); +} + +inline Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetLineNumber()); +} + +inline Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetStartColumn()); +} + +inline Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetEndColumn()); +} + +inline MaybeLocal<v8::Object> CloneElementAt( + v8::Handle<v8::Array> array + , uint32_t index) { + return MaybeLocal<v8::Object>(array->CloneElementAt(index)); +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::Function> fun + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv)); +} + +#endif // NAN_MAYBE_PRE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_new.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_new.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf8bbe40b9b72c39ee9d4f00bdfc8bb7be6f7f6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_new.h @@ -0,0 +1,340 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_NEW_H_ +#define NAN_NEW_H_ + +namespace imp { // scnr + +// TODO(agnat): Generalize +template <typename T> v8::Local<T> To(v8::Local<v8::Integer> i); + +template <> +inline +v8::Local<v8::Integer> +To<v8::Integer>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Integer>(i).ToLocalChecked(); +} + +template <> +inline +v8::Local<v8::Int32> +To<v8::Int32>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Int32>(i).ToLocalChecked(); +} + +template <> +inline +v8::Local<v8::Uint32> +To<v8::Uint32>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Uint32>(i).ToLocalChecked(); +} + +template <typename T> struct FactoryBase { + typedef v8::Local<T> return_t; +}; + +template <typename T> struct MaybeFactoryBase { + typedef MaybeLocal<T> return_t; +}; + +template <typename T> struct Factory; + +template <> +struct Factory<v8::Array> : FactoryBase<v8::Array> { + static inline return_t New(); + static inline return_t New(int length); +}; + +template <> +struct Factory<v8::Boolean> : FactoryBase<v8::Boolean> { + static inline return_t New(bool value); +}; + +template <> +struct Factory<v8::BooleanObject> : FactoryBase<v8::BooleanObject> { + static inline return_t New(bool value); +}; + +template <> +struct Factory<v8::Context> : FactoryBase<v8::Context> { + static inline + return_t + New( v8::ExtensionConfiguration* extensions = NULL + , v8::Local<v8::ObjectTemplate> tmpl = v8::Local<v8::ObjectTemplate>() + , v8::Local<v8::Value> obj = v8::Local<v8::Value>()); +}; + +template <> +struct Factory<v8::Date> : MaybeFactoryBase<v8::Date> { + static inline return_t New(double value); +}; + +template <> +struct Factory<v8::External> : FactoryBase<v8::External> { + static inline return_t New(void *value); +}; + +template <> +struct Factory<v8::Function> : FactoryBase<v8::Function> { + static inline + return_t + New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()); +}; + +template <> +struct Factory<v8::FunctionTemplate> : FactoryBase<v8::FunctionTemplate> { + static inline + return_t + New( FunctionCallback callback = NULL + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::Local<v8::Signature> signature = v8::Local<v8::Signature>()); +}; + +template <> +struct Factory<v8::Number> : FactoryBase<v8::Number> { + static inline return_t New(double value); +}; + +template <> +struct Factory<v8::NumberObject> : FactoryBase<v8::NumberObject> { + static inline return_t New(double value); +}; + +template <typename T> +struct IntegerFactory : FactoryBase<T> { + typedef typename FactoryBase<T>::return_t return_t; + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory<v8::Integer> : IntegerFactory<v8::Integer> {}; + +template <> +struct Factory<v8::Int32> : IntegerFactory<v8::Int32> {}; + +template <> +struct Factory<v8::Uint32> : FactoryBase<v8::Uint32> { + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory<v8::Object> : FactoryBase<v8::Object> { + static inline return_t New(); +}; + +template <> +struct Factory<v8::ObjectTemplate> : FactoryBase<v8::ObjectTemplate> { + static inline return_t New(); +}; + +template <> +struct Factory<v8::RegExp> : MaybeFactoryBase<v8::RegExp> { + static inline return_t New( + v8::Local<v8::String> pattern, v8::RegExp::Flags flags); +}; + +template <> +struct Factory<v8::Script> : MaybeFactoryBase<v8::Script> { + static inline return_t New( v8::Local<v8::String> source); + static inline return_t New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin); +}; + +template <> +struct Factory<v8::Signature> : FactoryBase<v8::Signature> { + typedef v8::Local<v8::FunctionTemplate> FTH; + static inline return_t New(FTH receiver = FTH()); +}; + +template <> +struct Factory<v8::String> : MaybeFactoryBase<v8::String> { + static inline return_t New(); + static inline return_t New(const char *value, int length = -1); + static inline return_t New(const uint16_t *value, int length = -1); + static inline return_t New(std::string const& value); + + static inline return_t New(v8::String::ExternalStringResource * value); + static inline return_t New(ExternalOneByteStringResource * value); +}; + +template <> +struct Factory<v8::StringObject> : FactoryBase<v8::StringObject> { + static inline return_t New(v8::Local<v8::String> value); +}; + +} // end of namespace imp + +#if (NODE_MODULE_VERSION >= 12) + +namespace imp { + +template <> +struct Factory<v8::UnboundScript> : MaybeFactoryBase<v8::UnboundScript> { + static inline return_t New( v8::Local<v8::String> source); + static inline return_t New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin); +}; + +} // end of namespace imp + +# include "nan_implementation_12_inl.h" + +#else // NODE_MODULE_VERSION >= 12 + +# include "nan_implementation_pre_12_inl.h" + +#endif + +//=== API ====================================================================== + +template <typename T> +typename imp::Factory<T>::return_t +New() { + return imp::Factory<T>::New(); +} + +template <typename T, typename A0> +typename imp::Factory<T>::return_t +New(A0 arg0) { + return imp::Factory<T>::New(arg0); +} + +template <typename T, typename A0, typename A1> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1) { + return imp::Factory<T>::New(arg0, arg1); +} + +template <typename T, typename A0, typename A1, typename A2> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1, A2 arg2) { + return imp::Factory<T>::New(arg0, arg1, arg2); +} + +template <typename T, typename A0, typename A1, typename A2, typename A3> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { + return imp::Factory<T>::New(arg0, arg1, arg2, arg3); +} + +// Note(agnat): When passing overloaded function pointers to template functions +// as generic arguments the compiler needs help in picking the right overload. +// These two functions handle New<Function> and New<FunctionTemplate> with +// all argument variations. + +// v8::Function and v8::FunctionTemplate with one or two arguments +template <typename T> +typename imp::Factory<T>::return_t +New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + return imp::Factory<T>::New(callback, data); +} + +// v8::Function and v8::FunctionTemplate with three arguments +template <typename T, typename A2> +typename imp::Factory<T>::return_t +New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , A2 a2 = A2()) { + return imp::Factory<T>::New(callback, data, a2); +} + +// Convenience + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template <typename T> inline v8::Local<T> New(v8::Handle<T> h); +#endif + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +template <typename T, typename M> + inline v8::Local<T> New(v8::Persistent<T, M> const& p); +#else +template <typename T> inline v8::Local<T> New(v8::Persistent<T> const& p); +#endif +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p); +template <typename T> +inline v8::Local<T> New(Global<T> const& p); + +inline +imp::Factory<v8::Boolean>::return_t +New(bool value) { + return New<v8::Boolean>(value); +} + +inline +imp::Factory<v8::Int32>::return_t +New(int32_t value) { + return New<v8::Int32>(value); +} + +inline +imp::Factory<v8::Uint32>::return_t +New(uint32_t value) { + return New<v8::Uint32>(value); +} + +inline +imp::Factory<v8::Number>::return_t +New(double value) { + return New<v8::Number>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(std::string const& value) { // NOLINT(build/include_what_you_use) + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(const char * value, int length) { + return New<v8::String>(value, length); +} + +inline +imp::Factory<v8::String>::return_t +New(const uint16_t * value, int length) { + return New<v8::String>(value, length); +} + +inline +imp::Factory<v8::String>::return_t +New(const char * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(const uint16_t * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(v8::String::ExternalStringResource * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(ExternalOneByteStringResource * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::RegExp>::return_t +New(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) { + return New<v8::RegExp>(pattern, flags); +} + +#endif // NAN_NEW_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_object_wrap.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_object_wrap.h new file mode 100644 index 0000000000000000000000000000000000000000..a4d96178f0b0a2d44a24a5563699795beec18954 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_object_wrap.h @@ -0,0 +1,155 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_OBJECT_WRAP_H_ +#define NAN_OBJECT_WRAP_H_ + +class ObjectWrap { + public: + ObjectWrap() { + refs_ = 0; + } + + + virtual ~ObjectWrap() { + if (persistent().IsEmpty()) { + return; + } + + assert(persistent().IsNearDeath()); + persistent().ClearWeak(); + persistent().Reset(); + } + + + template <class T> + static inline T* Unwrap(v8::Local<v8::Object> object) { + assert(!object.IsEmpty()); + assert(object->InternalFieldCount() > 0); + // Cast to ObjectWrap before casting to T. A direct cast from void + // to T won't work right when T has more than one base class. + void* ptr = GetInternalFieldPointer(object, 0); + ObjectWrap* wrap = static_cast<ObjectWrap*>(ptr); + return static_cast<T*>(wrap); + } + + + inline v8::Local<v8::Object> handle() const { + return New(handle_); + } + + + inline Persistent<v8::Object>& persistent() { + return handle_; + } + + + protected: + inline void Wrap(v8::Local<v8::Object> object) { + assert(persistent().IsEmpty()); + assert(object->InternalFieldCount() > 0); + SetInternalFieldPointer(object, 0, this); + persistent().Reset(object); + MakeWeak(); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + inline void MakeWeak() { + persistent().v8::PersistentBase<v8::Object>::SetWeak( + this, WeakCallback, v8::WeakCallbackType::kParameter); + persistent().MarkIndependent(); + } + +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + + inline void MakeWeak() { + persistent().v8::PersistentBase<v8::Object>::SetWeak(this, WeakCallback); + persistent().MarkIndependent(); + } + +#else + + inline void MakeWeak() { + persistent().persistent.MakeWeak(this, WeakCallback); + persistent().MarkIndependent(); + } + +#endif + + /* Ref() marks the object as being attached to an event loop. + * Refed objects will not be garbage collected, even if + * all references are lost. + */ + virtual void Ref() { + assert(!persistent().IsEmpty()); + persistent().ClearWeak(); + refs_++; + } + + /* Unref() marks an object as detached from the event loop. This is its + * default state. When an object with a "weak" reference changes from + * attached to detached state it will be freed. Be careful not to access + * the object after making this call as it might be gone! + * (A "weak reference" means an object that only has a + * persistant handle.) + * + * DO NOT CALL THIS FROM DESTRUCTOR + */ + virtual void Unref() { + assert(!persistent().IsEmpty()); + assert(!persistent().IsWeak()); + assert(refs_ > 0); + if (--refs_ == 0) + MakeWeak(); + } + + int refs_; // ro + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap) +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + static void + WeakCallback(v8::WeakCallbackInfo<ObjectWrap> const& info) { + ObjectWrap* wrap = info.GetParameter(); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + + static void + WeakCallback(v8::WeakCallbackData<v8::Object, ObjectWrap> const& data) { + ObjectWrap* wrap = data.GetParameter(); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#else + + static void WeakCallback(v8::Persistent<v8::Value> value, void *data) { + ObjectWrap *wrap = static_cast<ObjectWrap*>(data); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#endif + Persistent<v8::Object> handle_; +}; + + +#endif // NAN_OBJECT_WRAP_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..d9649e867606c6356e393e9964b5607a08ea4e3a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_12_inl.h @@ -0,0 +1,132 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PERSISTENT_12_INL_H_ +#define NAN_PERSISTENT_12_INL_H_ + +template<typename T, typename M> class Persistent : + public v8::Persistent<T, M> { + public: + inline Persistent() : v8::Persistent<T, M>() {} + + template<typename S> inline Persistent(v8::Local<S> that) : + v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {} + + template<typename S, typename M2> + inline + Persistent(const v8::Persistent<S, M2> &that) : // NOLINT(runtime/explicit) + v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type); + + private: + inline T *operator*() const { return *PersistentBase<T>::persistent; } + + template<typename S, typename M2> + inline void Copy(const Persistent<S, M2> &that) { + TYPE_CHECK(T, S); + + this->Reset(); + + if (!that.IsEmpty()) { + this->Reset(that); + M::Copy(that, this); + } + } +}; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +template<typename T> +class Global : public v8::Global<T> { + public: + inline Global() : v8::Global<T>() {} + + template<typename S> inline Global(v8::Local<S> that) : + v8::Global<T>(v8::Isolate::GetCurrent(), that) {} + + template<typename S> + inline + Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) + v8::Global<S>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + reinterpret_cast<Persistent<T>*>(this)->SetWeak( + parameter, callback, type); + } +}; +#else +template<typename T> +class Global : public v8::UniquePersistent<T> { + public: + inline Global() : v8::UniquePersistent<T>() {} + + template<typename S> inline Global(v8::Local<S> that) : + v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {} + + template<typename S> + inline + Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) + v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + reinterpret_cast<Persistent<T>*>(this)->SetWeak( + parameter, callback, type); + } +}; +#endif + +#endif // NAN_PERSISTENT_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..4c9c59da70b66a8c2090cfefa9078fb886bcf646 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_persistent_pre_12_inl.h @@ -0,0 +1,242 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PERSISTENT_PRE_12_INL_H_ +#define NAN_PERSISTENT_PRE_12_INL_H_ + +template<typename T> +class PersistentBase { + v8::Persistent<T> persistent; + template<typename U> + friend v8::Local<U> New(const PersistentBase<U> &p); + template<typename U, typename M> + friend v8::Local<U> New(const Persistent<U, M> &p); + template<typename U> + friend v8::Local<U> New(const Global<U> &p); + template<typename S> friend class ReturnValue; + + public: + inline PersistentBase() : + persistent() {} + + inline void Reset() { + persistent.Dispose(); + persistent.Clear(); + } + + template<typename S> + inline void Reset(const v8::Local<S> &other) { + TYPE_CHECK(T, S); + + if (!persistent.IsEmpty()) { + persistent.Dispose(); + } + + if (other.IsEmpty()) { + persistent.Clear(); + } else { + persistent = v8::Persistent<T>::New(other); + } + } + + template<typename S> + inline void Reset(const PersistentBase<S> &other) { + TYPE_CHECK(T, S); + + if (!persistent.IsEmpty()) { + persistent.Dispose(); + } + + if (other.IsEmpty()) { + persistent.Clear(); + } else { + persistent = v8::Persistent<T>::New(other.persistent); + } + } + + inline bool IsEmpty() const { return persistent.IsEmpty(); } + + inline void Empty() { persistent.Clear(); } + + template<typename S> + inline bool operator==(const PersistentBase<S> &that) const { + return this->persistent == that.persistent; + } + + template<typename S> + inline bool operator==(const v8::Local<S> &that) const { + return this->persistent == that; + } + + template<typename S> + inline bool operator!=(const PersistentBase<S> &that) const { + return !operator==(that); + } + + template<typename S> + inline bool operator!=(const v8::Local<S> &that) const { + return !operator==(that); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type); + + inline void ClearWeak() { persistent.ClearWeak(); } + + inline void MarkIndependent() { persistent.MarkIndependent(); } + + inline bool IsIndependent() const { return persistent.IsIndependent(); } + + inline bool IsNearDeath() const { return persistent.IsNearDeath(); } + + inline bool IsWeak() const { return persistent.IsWeak(); } + + private: + inline explicit PersistentBase(v8::Persistent<T> that) : + persistent(that) { } + inline explicit PersistentBase(T *val) : persistent(val) {} + template<typename S, typename M> friend class Persistent; + template<typename S> friend class Global; + friend class ObjectWrap; +}; + +template<typename T> +class NonCopyablePersistentTraits { + public: + typedef Persistent<T, NonCopyablePersistentTraits<T> > + NonCopyablePersistent; + static const bool kResetInDestructor = false; + template<typename S, typename M> + inline static void Copy(const Persistent<S, M> &source, + NonCopyablePersistent *dest) { + Uncompilable<v8::Object>(); + } + + template<typename O> inline static void Uncompilable() { + TYPE_CHECK(O, v8::Primitive); + } +}; + +template<typename T> +struct CopyablePersistentTraits { + typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent; + static const bool kResetInDestructor = true; + template<typename S, typename M> + static inline void Copy(const Persistent<S, M> &source, + CopyablePersistent *dest) {} +}; + +template<typename T, typename M> class Persistent : + public PersistentBase<T> { + public: + inline Persistent() {} + + template<typename S> inline Persistent(v8::Handle<S> that) + : PersistentBase<T>(v8::Persistent<T>::New(that)) { + TYPE_CHECK(T, S); + } + + inline Persistent(const Persistent &that) : PersistentBase<T>() { + Copy(that); + } + + template<typename S, typename M2> + inline Persistent(const Persistent<S, M2> &that) : + PersistentBase<T>() { + Copy(that); + } + + inline Persistent &operator=(const Persistent &that) { + Copy(that); + return *this; + } + + template <class S, class M2> + inline Persistent &operator=(const Persistent<S, M2> &that) { + Copy(that); + return *this; + } + + inline ~Persistent() { + if (M::kResetInDestructor) this->Reset(); + } + + private: + inline T *operator*() const { return *PersistentBase<T>::persistent; } + + template<typename S, typename M2> + inline void Copy(const Persistent<S, M2> &that) { + TYPE_CHECK(T, S); + + this->Reset(); + + if (!that.IsEmpty()) { + this->persistent = v8::Persistent<T>::New(that.persistent); + M::Copy(that, this); + } + } +}; + +template<typename T> +class Global : public PersistentBase<T> { + struct RValue { + inline explicit RValue(Global* obj) : object(obj) {} + Global* object; + }; + + public: + inline Global() : PersistentBase<T>(0) { } + + template <typename S> + inline Global(v8::Local<S> that) // NOLINT(runtime/explicit) + : PersistentBase<T>(v8::Persistent<T>::New(that)) { + TYPE_CHECK(T, S); + } + + template <typename S> + inline Global(const PersistentBase<S> &that) // NOLINT(runtime/explicit) + : PersistentBase<T>(that) { + TYPE_CHECK(T, S); + } + /** + * Move constructor. + */ + inline Global(RValue rvalue) // NOLINT(runtime/explicit) + : PersistentBase<T>(rvalue.object->persistent) { + rvalue.object->Reset(); + } + inline ~Global() { this->Reset(); } + /** + * Move via assignment. + */ + template<typename S> + inline Global &operator=(Global<S> rhs) { + TYPE_CHECK(T, S); + this->Reset(rhs.persistent); + rhs.Reset(); + return *this; + } + /** + * Cast operator for moves. + */ + inline operator RValue() { return RValue(this); } + /** + * Pass allows returning uniques from functions, etc. + */ + Global Pass() { return Global(RValue(this)); } + + private: + Global(Global &); + void operator=(Global &); + template<typename S> friend class ReturnValue; +}; + +#endif // NAN_PERSISTENT_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_private.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_private.h new file mode 100644 index 0000000000000000000000000000000000000000..15f44cc8c293861d46c73274e32b910f05011986 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_private.h @@ -0,0 +1,73 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PRIVATE_H_ +#define NAN_PRIVATE_H_ + +inline Maybe<bool> +HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { + HandleScope scope; +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->HasPrivate(context, private_key); +#else + return Just(!object->GetHiddenValue(key).IsEmpty()); +#endif +} + +inline MaybeLocal<v8::Value> +GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + v8::MaybeLocal<v8::Value> v = object->GetPrivate(context, private_key); + return scope.Escape(v.ToLocalChecked()); +#else + EscapableHandleScope scope; + v8::Local<v8::Value> v = object->GetHiddenValue(key); + if (v.IsEmpty()) { + v = Undefined(); + } + return scope.Escape(v); +#endif +} + +inline Maybe<bool> SetPrivate( + v8::Local<v8::Object> object, + v8::Local<v8::String> key, + v8::Local<v8::Value> value) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + HandleScope scope; + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->SetPrivate(context, private_key, value); +#else + return Just(object->SetHiddenValue(key, value)); +#endif +} + +inline Maybe<bool> DeletePrivate( + v8::Local<v8::Object> object, + v8::Local<v8::String> key) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + HandleScope scope; + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->DeletePrivate(isolate->GetCurrentContext(), private_key); +#else + return Just(object->DeleteHiddenValue(key)); +#endif +} + +#endif // NAN_PRIVATE_H_ + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_string_bytes.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_string_bytes.h new file mode 100644 index 0000000000000000000000000000000000000000..a2e6437d12b74cd29fad17ed6c40e1e739eded2c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_string_bytes.h @@ -0,0 +1,305 @@ +// 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. + +#ifndef NAN_STRING_BYTES_H_ +#define NAN_STRING_BYTES_H_ + +// Decodes a v8::Local<v8::String> or Buffer to a raw char* + +namespace imp { + +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + + +//// Base 64 //// + +#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + + + +//// HEX //// + +static bool contains_non_ascii_slow(const char* buf, size_t len) { + for (size_t i = 0; i < len; ++i) { + if (buf[i] & 0x80) return true; + } + return false; +} + + +static bool contains_non_ascii(const char* src, size_t len) { + if (len < 16) { + return contains_non_ascii_slow(src, len); + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask; + + if (unaligned > 0) { + const unsigned n = bytes_per_word - unaligned; + if (contains_non_ascii_slow(src, n)) return true; + src += n; + len -= n; + } + + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = 0x8080808080808080ll; +#else + const uintptr_t mask = 0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + if (srcw[i] & mask) return true; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + if (contains_non_ascii_slow(src + offset, remainder)) return true; + } + + return false; +} + + +static void force_ascii_slow(const char* src, char* dst, size_t len) { + for (size_t i = 0; i < len; ++i) { + dst[i] = src[i] & 0x7f; + } +} + + +static void force_ascii(const char* src, char* dst, size_t len) { + if (len < 16) { + force_ascii_slow(src, dst, len); + return; + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask; + const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask; + + if (src_unalign > 0) { + if (src_unalign == dst_unalign) { + const unsigned unalign = bytes_per_word - src_unalign; + force_ascii_slow(src, dst, unalign); + src += unalign; + dst += unalign; + len -= src_unalign; + } else { + force_ascii_slow(src, dst, len); + return; + } + } + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = ~0x8080808080808080ll; +#else + const uintptr_t mask = ~0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src); + uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + dstw[i] = srcw[i] & mask; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + force_ascii_slow(src + offset, dst + offset, remainder); + } +} + + +static size_t base64_encode(const char* src, + size_t slen, + char* dst, + size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= base64_encoded_size(slen) && + "not enough space provided for base64 encode"); + + dlen = base64_encoded_size(slen); + + unsigned a; + unsigned b; + unsigned c; + unsigned i; + unsigned k; + unsigned n; + + static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + i = 0; + k = 0; + n = slen / 3 * 3; + + while (i < n) { + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + c = src[i + 2] & 0xff; + + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; + dst[k + 3] = table[c & 0x3f]; + + i += 3; + k += 4; + } + + if (n != slen) { + switch (slen - n) { + case 1: + a = src[i + 0] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[(a & 3) << 4]; + dst[k + 2] = '='; + dst[k + 3] = '='; + break; + + case 2: + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[(b & 0x0f) << 2]; + dst[k + 3] = '='; + break; + } + } + + return dlen; +} + + +static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= slen * 2 && + "not enough space provided for hex encode"); + + dlen = slen * 2; + for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { + static const char hex[] = "0123456789abcdef"; + uint8_t val = static_cast<uint8_t>(src[i]); + dst[k + 0] = hex[val >> 4]; + dst[k + 1] = hex[val & 15]; + } + + return dlen; +} + + + +static Local<Value> Encode(const char* buf, + size_t buflen, + enum Encoding encoding) { + assert(buflen <= node::Buffer::kMaxLength); + if (!buflen && encoding != BUFFER) + return New("").ToLocalChecked(); + + Local<String> val; + switch (encoding) { + case BUFFER: + return CopyBuffer(buf, buflen).ToLocalChecked(); + + case ASCII: + if (contains_non_ascii(buf, buflen)) { + char* out = new char[buflen]; + force_ascii(buf, out, buflen); + val = New<String>(out, buflen).ToLocalChecked(); + delete[] out; + } else { + val = New<String>(buf, buflen).ToLocalChecked(); + } + break; + + case UTF8: + val = New<String>(buf, buflen).ToLocalChecked(); + break; + + case BINARY: { + // TODO(isaacs) use ExternalTwoByteString? + const unsigned char *cbuf = reinterpret_cast<const unsigned char*>(buf); + uint16_t * twobytebuf = new uint16_t[buflen]; + for (size_t i = 0; i < buflen; i++) { + // XXX is the following line platform independent? + twobytebuf[i] = cbuf[i]; + } + val = New<String>(twobytebuf, buflen).ToLocalChecked(); + delete[] twobytebuf; + break; + } + + case BASE64: { + size_t dlen = base64_encoded_size(buflen); + char* dst = new char[dlen]; + + size_t written = base64_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = New<String>(dst, dlen).ToLocalChecked(); + delete[] dst; + break; + } + + case UCS2: { + const uint16_t* data = reinterpret_cast<const uint16_t*>(buf); + val = New<String>(data, buflen / 2).ToLocalChecked(); + break; + } + + case HEX: { + size_t dlen = buflen * 2; + char* dst = new char[dlen]; + size_t written = hex_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = New<String>(dst, dlen).ToLocalChecked(); + delete[] dst; + break; + } + + default: + assert(0 && "unknown encoding"); + break; + } + + return val; +} + +#undef base64_encoded_size + +} // end of namespace imp + +#endif // NAN_STRING_BYTES_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_typedarray_contents.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_typedarray_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..d28ae323e2276b43733be5cac407fd28b91e55c7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_typedarray_contents.h @@ -0,0 +1,90 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_TYPEDARRAY_CONTENTS_H_ +#define NAN_TYPEDARRAY_CONTENTS_H_ + +template<typename T> +class TypedArrayContents { + public: + inline explicit TypedArrayContents(v8::Local<v8::Value> from) : + length_(0), data_(NULL) { + HandleScope scope; + + size_t length = 0; + void* data = NULL; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + if (from->IsArrayBufferView()) { + v8::Local<v8::ArrayBufferView> array = + v8::Local<v8::ArrayBufferView>::Cast(from); + + const size_t byte_length = array->ByteLength(); + const ptrdiff_t byte_offset = array->ByteOffset(); + v8::Local<v8::ArrayBuffer> buffer = array->Buffer(); + + length = byte_length / sizeof(T); + data = static_cast<char*>(buffer->GetContents().Data()) + byte_offset; + } + +#else + + if (from->IsObject() && !from->IsNull()) { + v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from); + + MaybeLocal<v8::Value> buffer = Get(array, + New<v8::String>("buffer").ToLocalChecked()); + MaybeLocal<v8::Value> byte_length = Get(array, + New<v8::String>("byteLength").ToLocalChecked()); + MaybeLocal<v8::Value> byte_offset = Get(array, + New<v8::String>("byteOffset").ToLocalChecked()); + + if (!buffer.IsEmpty() && + !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() && + !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) { + data = array->GetIndexedPropertiesExternalArrayData(); + if(data) { + length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T); + } + } + } + +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L + assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0); +#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__) + assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0); +#else + assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0); +#endif + + length_ = length; + data_ = static_cast<T*>(data); + } + + inline size_t length() const { return length_; } + inline T* operator*() { return data_; } + inline const T* operator*() const { return data_; } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents) + + //Disable heap allocation + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } + + size_t length_; + T* data_; +}; + +#endif // NAN_TYPEDARRAY_CONTENTS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_weak.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_weak.h new file mode 100644 index 0000000000000000000000000000000000000000..744ffd6ea0a47bb9b6a01865ee45807d50ca2a1f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/nan_weak.h @@ -0,0 +1,432 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_WEAK_H_ +#define NAN_WEAK_H_ + +static const int kInternalFieldsInWeakCallback = 2; +static const int kNoInternalFieldIndex = -1; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::WeakCallbackInfo<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::PhantomCallbackData<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::PhantomCallbackData<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + v8::InternalFieldsCallbackData<WeakCallbackInfo<T>, void> const& +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# define NAN_WEAK_CALLBACK_DATA_TYPE_ \ + v8::WeakCallbackData<S, WeakCallbackInfo<T> > const& +# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_ +#else +# define NAN_WEAK_CALLBACK_DATA_TYPE_ void * +# define NAN_WEAK_CALLBACK_SIG_ \ + v8::Persistent<v8::Value>, NAN_WEAK_CALLBACK_DATA_TYPE_ +#endif + +template<typename T> +class WeakCallbackInfo { + public: + typedef void (*Callback)(const WeakCallbackInfo<T>& data); + WeakCallbackInfo( + Persistent<v8::Value> *persistent + , Callback callback + , void *parameter + , void *field1 = 0 + , void *field2 = 0) : + callback_(callback), isolate_(0), parameter_(parameter) { + std::memcpy(&persistent_, persistent, sizeof (v8::Persistent<v8::Value>)); + internal_fields_[0] = field1; + internal_fields_[1] = field2; + } + inline v8::Isolate *GetIsolate() const { return isolate_; } + inline T *GetParameter() const { return static_cast<T*>(parameter_); } + inline void *GetInternalField(int index) const { + assert((index == 0 || index == 1) && "internal field index out of bounds"); + if (index == 0) { + return internal_fields_[0]; + } else { + return internal_fields_[1]; + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo) + Callback callback_; + v8::Isolate *isolate_; + void *parameter_; + void *internal_fields_[kInternalFieldsInWeakCallback]; + v8::Persistent<v8::Value> persistent_; + template<typename S, typename M> friend class Persistent; + template<typename S> friend class PersistentBase; +#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION +# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + template<typename S> + static void invoke(NAN_WEAK_CALLBACK_SIG_ data); + template<typename S> + static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); +# else + static void invoke(NAN_WEAK_CALLBACK_SIG_ data); + static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); +# endif +#else +# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + template<bool isFirstPass> + static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); + template<bool isFirstPass> + static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); +# else + static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); + static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); +# endif + static WeakCallbackInfo *unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data); + static WeakCallbackInfo *unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data); +#endif +}; + + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + +template<typename T> +template<bool isFirstPass> +void +WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrapparameter(data); + if (isFirstPass) { + cbinfo->persistent_.Reset(); + data.SetSecondPassCallback(invokeparameter<false>); + } else { + cbinfo->callback_(*cbinfo); + delete cbinfo; + } +} + +template<typename T> +template<bool isFirstPass> +void +WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwraptwofield(data); + if (isFirstPass) { + cbinfo->persistent_.Reset(); + data.SetSecondPassCallback(invoketwofield<false>); + } else { + cbinfo->callback_(*cbinfo); + delete cbinfo; + } +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetParameter()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetInternalField(0)); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ +#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + +template<typename T> +void +WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrapparameter(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +void +WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwraptwofield(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetParameter()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetInternalField1()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ +#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + +template<typename T> +template<typename S> +void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrap(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +template<typename S> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap( + NAN_WEAK_CALLBACK_DATA_TYPE_ data) { + void *parameter = data.GetParameter(); + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(parameter); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_CALLBACK_SIG_ +#undef NAN_WEAK_CALLBACK_DATA_TYPE_ +#else + +template<typename T> +void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrap(data); + cbinfo->persistent_.Dispose(); + cbinfo->persistent_.Clear(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap( + NAN_WEAK_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data); + cbinfo->isolate_ = v8::Isolate::GetCurrent(); + return cbinfo; +} + +#undef NAN_WEAK_CALLBACK_SIG_ +#undef NAN_WEAK_CALLBACK_DATA_TYPE_ +#endif + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetWeak( + wcbd + , WeakCallbackInfo<P>::template invokeparameter<true> + , type); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetWeak( + static_cast<WeakCallbackInfo<P>*>(0) + , WeakCallbackInfo<P>::template invoketwofield<true> + , type); + } +} +#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetPhantom( + wcbd + , WeakCallbackInfo<P>::invokeparameter); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetPhantom( + static_cast<WeakCallbackInfo<P>*>(0) + , WeakCallbackInfo<P>::invoketwofield + , 0 + , count > 1 ? 1 : kNoInternalFieldIndex); + } +} +#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetPhantom( + wcbd + , WeakCallbackInfo<P>::invokeparameter); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetPhantom( + WeakCallbackInfo<P>::invoketwofield + , 0 + , count > 1 ? 1 : kNoInternalFieldIndex); + } +} +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke); + } +} +#else +template<typename T> +template<typename P> +inline void PersistentBase<T>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke); + } +} +#endif + +#endif // NAN_WEAK_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/package.json new file mode 100644 index 0000000000000000000000000000000000000000..442fbbf68f6bb09ec7421ccc4bd8a76871e88483 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/package.json @@ -0,0 +1,97 @@ +{ + "_from": "nan@^2.3.3", + "_id": "nan@2.10.0", + "_inBundle": false, + "_integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", + "_location": "/nan", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "nan@^2.3.3", + "name": "nan", + "escapedName": "nan", + "rawSpec": "^2.3.3", + "saveSpec": null, + "fetchSpec": "^2.3.3" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "_shasum": "96d0cd610ebd58d4b4de9cc0c6828cda99c7548f", + "_spec": "nan@^2.3.3", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "bugs": { + "url": "https://github.com/nodejs/nan/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + { + "name": "Benjamin Byholm", + "email": "bbyholm@abo.fi", + "url": "https://github.com/kkoopa/" + }, + { + "name": "Trevor Norris", + "email": "trev.norris@gmail.com", + "url": "https://github.com/trevnorris" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "https://github.com/TooTallNate" + }, + { + "name": "Brett Lawson", + "email": "brett19@gmail.com", + "url": "https://github.com/brett19" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl", + "url": "https://github.com/bnoordhuis" + }, + { + "name": "David Siegel", + "email": "david@artcom.de", + "url": "https://github.com/agnat" + }, + { + "name": "Michael Ira Krufky", + "email": "mkrufky@gmail.com", + "url": "https://github.com/mkrufky" + } + ], + "deprecated": false, + "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 9 compatibility", + "devDependencies": { + "bindings": "~1.2.1", + "commander": "^2.8.1", + "glob": "^5.0.14", + "node-gyp": "~3.6.2", + "readable-stream": "^2.1.4", + "request": "=2.81.0", + "tap": "~0.7.1", + "xtend": "~4.0.0" + }, + "homepage": "https://github.com/nodejs/nan#readme", + "license": "MIT", + "main": "include_dirs.js", + "name": "nan", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "scripts": { + "docs": "doc/.build.sh", + "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test", + "test": "tap --gc --stderr test/js/*-test.js" + }, + "version": "2.10.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/1to2.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/1to2.js new file mode 100644 index 0000000000000000000000000000000000000000..337f8bf2c2bed35071f44064780364d66208d5d3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/1to2.js @@ -0,0 +1,412 @@ +#!/usr/bin/env node +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +var commander = require('commander'), + fs = require('fs'), + glob = require('glob'), + groups = [], + total = 0, + warning1 = '/* ERROR: Rewrite using Buffer */\n', + warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n', + length, + i; + +fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) { + if (err) { + throw err; + } + + commander + .version(JSON.parse(data).version) + .usage('[options] <file ...>') + .parse(process.argv); + + if (!process.argv.slice(2).length) { + commander.outputHelp(); + } +}); + +/* construct strings representing regular expressions + each expression contains a unique group allowing for identification of the match + the index of this key group, relative to the regular expression in question, + is indicated by the first array member */ + +/* simple substistutions, key group is the entire match, 0 */ +groups.push([0, [ + '_NAN_', + 'NODE_SET_METHOD', + 'NODE_SET_PROTOTYPE_METHOD', + 'NanAsciiString', + 'NanEscapeScope', + 'NanReturnValue', + 'NanUcs2String'].join('|')]); + +/* substitutions of parameterless macros, key group is 1 */ +groups.push([1, ['(', [ + 'NanEscapableScope', + 'NanReturnNull', + 'NanReturnUndefined', + 'NanScope'].join('|'), ')\\(\\)'].join('')]); + +/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ +groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); + +/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ +groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); + +/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ +groups.push([2, ['(', warning2, ')?', '^.*?(', [ + 'GetIndexedPropertiesExternalArrayDataLength', + 'GetIndexedPropertiesExternalArrayData', + 'GetIndexedPropertiesExternalArrayDataType', + 'GetIndexedPropertiesPixelData', + 'GetIndexedPropertiesPixelDataLength', + 'HasIndexedPropertiesInExternalArrayData', + 'HasIndexedPropertiesInPixelData', + 'SetIndexedPropertiesToExternalArrayData', + 'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]); + +/* No need for NanScope in V8-exposed methods, key group 2 */ +groups.push([2, ['((', [ + 'NAN_METHOD', + 'NAN_GETTER', + 'NAN_SETTER', + 'NAN_PROPERTY_GETTER', + 'NAN_PROPERTY_SETTER', + 'NAN_PROPERTY_ENUMERATOR', + 'NAN_PROPERTY_DELETER', + 'NAN_PROPERTY_QUERY', + 'NAN_INDEX_GETTER', + 'NAN_INDEX_SETTER', + 'NAN_INDEX_ENUMERATOR', + 'NAN_INDEX_DELETER', + 'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]); + +/* v8::Value::ToXXXXXXX returns v8::MaybeLocal<T>, key group 3 */ +groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [ + 'Boolean', + 'Number', + 'String', + 'Object', + 'Integer', + 'Uint32', + 'Int32'].join('|'), ')\\('].join('')]); + +/* v8::Value::XXXXXXXValue returns v8::Maybe<T>, key group 3 */ +groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [ + 'Boolean', + 'Number', + 'Integer', + 'Uint32', + 'Int32'].join('|'), ')Value)\\('].join('')]); + +/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */ +groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']); + +/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */ +groups.push([1, ['(', [ + 'NanDisposePersistent', + 'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]); + +/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */ +groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']); + +/* Many methods of v8::Object and others now return v8::MaybeLocal<T>, key group 3 */ +groups.push([3, ['([\\s])([^\\s]+)->(', [ + 'GetEndColumn', + 'GetFunction', + 'GetLineNumber', + 'NewInstance', + 'GetPropertyNames', + 'GetOwnPropertyNames', + 'GetSourceLine', + 'GetStartColumn', + 'ObjectProtoToString', + 'ToArrayIndex', + 'ToDetailString', + 'CallAsConstructor', + 'CallAsFunction', + 'CloneElementAt', + 'Delete', + 'ForceSet', + 'Get', + 'GetPropertyAttributes', + 'GetRealNamedProperty', + 'GetRealNamedPropertyInPrototypeChain', + 'Has', + 'HasOwnProperty', + 'HasRealIndexedProperty', + 'HasRealNamedCallbackProperty', + 'HasRealNamedProperty', + 'Set', + 'SetAccessor', + 'SetIndexedPropertyHandler', + 'SetNamedPropertyHandler', + 'SetPrototype'].join('|'), ')\\('].join('')]); + +/* You should get an error if any of these fail anyways, + or handle the error better, it is indicated either way, key group 2 */ +groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); + +/* v8::Value::Equals now returns a v8::Maybe, key group 3 */ +groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']); + +/* NanPersistent makes this unnecessary, key group 1 */ +groups.push([1, '(NanAssignPersistent)(?:<v8\\:\\:[^>]+>)?\\(([^,]+),\\s*']); + +/* args has been renamed to info, key group 2 */ +groups.push([2, '(\\W)(args)(\\W)']) + +/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */ +groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']); + +/* v8::Persistent was replaced with NanPersistent, key group 2 */ +groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']); + +/* counts the number of capturing groups in a well-formed regular expression, + ignoring non-capturing groups and escaped parentheses */ +function groupcount(s) { + var positive = s.match(/\((?!\?)/g), + negative = s.match(/\\\(/g); + return (positive ? positive.length : 0) - (negative ? negative.length : 0); +} + +/* compute the absolute position of each key group in the joined master RegExp */ +for (i = 1, length = groups.length; i < length; i++) { + total += groupcount(groups[i - 1][1]); + groups[i][0] += total; +} + +/* create the master RegExp, whis is the union of all the groups' expressions */ +master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm'); + +/* replacement function for String.replace, receives 21 arguments */ +function replace() { + /* simple expressions */ + switch (arguments[groups[0][0]]) { + case '_NAN_': + return 'NAN_'; + case 'NODE_SET_METHOD': + return 'NanSetMethod'; + case 'NODE_SET_PROTOTYPE_METHOD': + return 'NanSetPrototypeMethod'; + case 'NanAsciiString': + return 'NanUtf8String'; + case 'NanEscapeScope': + return 'scope.Escape'; + case 'NanReturnNull': + return 'info.GetReturnValue().SetNull'; + case 'NanReturnValue': + return 'info.GetReturnValue().Set'; + case 'NanUcs2String': + return 'v8::String::Value'; + default: + } + + /* macros without arguments */ + switch (arguments[groups[1][0]]) { + case 'NanEscapableScope': + return 'NanEscapableScope scope' + case 'NanReturnUndefined': + return 'return'; + case 'NanScope': + return 'NanScope scope'; + default: + } + + /* TryCatch, emulate negative backref */ + if (arguments[groups[2][0]] === 'TryCatch') { + return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch'; + } + + /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */ + if (arguments[groups[3][0]] === 'NanNew') { + return [arguments[0], '.ToLocalChecked()'].join(''); + } + + /* insert warning for removed functions as comment on new line above */ + switch (arguments[groups[4][0]]) { + case 'GetIndexedPropertiesExternalArrayData': + case 'GetIndexedPropertiesExternalArrayDataLength': + case 'GetIndexedPropertiesExternalArrayDataType': + case 'GetIndexedPropertiesPixelData': + case 'GetIndexedPropertiesPixelDataLength': + case 'HasIndexedPropertiesInExternalArrayData': + case 'HasIndexedPropertiesInPixelData': + case 'SetIndexedPropertiesToExternalArrayData': + case 'SetIndexedPropertiesToPixelData': + return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); + default: + } + + /* remove unnecessary NanScope() */ + switch (arguments[groups[5][0]]) { + case 'NAN_GETTER': + case 'NAN_METHOD': + case 'NAN_SETTER': + case 'NAN_INDEX_DELETER': + case 'NAN_INDEX_ENUMERATOR': + case 'NAN_INDEX_GETTER': + case 'NAN_INDEX_QUERY': + case 'NAN_INDEX_SETTER': + case 'NAN_PROPERTY_DELETER': + case 'NAN_PROPERTY_ENUMERATOR': + case 'NAN_PROPERTY_GETTER': + case 'NAN_PROPERTY_QUERY': + case 'NAN_PROPERTY_SETTER': + return arguments[groups[5][0] - 1]; + default: + } + + /* Value converstion */ + switch (arguments[groups[6][0]]) { + case 'Boolean': + case 'Int32': + case 'Integer': + case 'Number': + case 'Object': + case 'String': + case 'Uint32': + return [arguments[groups[6][0] - 2], 'NanTo<v8::', arguments[groups[6][0]], '>(', arguments[groups[6][0] - 1]].join(''); + default: + } + + /* other value conversion */ + switch (arguments[groups[7][0]]) { + case 'BooleanValue': + return [arguments[groups[7][0] - 2], 'NanTo<bool>(', arguments[groups[7][0] - 1]].join(''); + case 'Int32Value': + return [arguments[groups[7][0] - 2], 'NanTo<int32_t>(', arguments[groups[7][0] - 1]].join(''); + case 'IntegerValue': + return [arguments[groups[7][0] - 2], 'NanTo<int64_t>(', arguments[groups[7][0] - 1]].join(''); + case 'Uint32Value': + return [arguments[groups[7][0] - 2], 'NanTo<uint32_t>(', arguments[groups[7][0] - 1]].join(''); + default: + } + + /* NAN_WEAK_CALLBACK */ + if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { + return ['template<typename T>\nvoid ', + arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo<T> &data)'].join(''); + } + + /* use methods on NAN classes instead */ + switch (arguments[groups[9][0]]) { + case 'NanDisposePersistent': + return [arguments[groups[9][0] + 1], '.Reset('].join(''); + case 'NanObjectWrapHandle': + return [arguments[groups[9][0] + 1], '->handle('].join(''); + default: + } + + /* use method on NanPersistent instead */ + if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { + return arguments[groups[10][0] + 1] + '.SetWeak('; + } + + /* These return Maybes, the upper ones take no arguments */ + switch (arguments[groups[11][0]]) { + case 'GetEndColumn': + case 'GetFunction': + case 'GetLineNumber': + case 'GetOwnPropertyNames': + case 'GetPropertyNames': + case 'GetSourceLine': + case 'GetStartColumn': + case 'NewInstance': + case 'ObjectProtoToString': + case 'ToArrayIndex': + case 'ToDetailString': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); + case 'CallAsConstructor': + case 'CallAsFunction': + case 'CloneElementAt': + case 'Delete': + case 'ForceSet': + case 'Get': + case 'GetPropertyAttributes': + case 'GetRealNamedProperty': + case 'GetRealNamedPropertyInPrototypeChain': + case 'Has': + case 'HasOwnProperty': + case 'HasRealIndexedProperty': + case 'HasRealNamedCallbackProperty': + case 'HasRealNamedProperty': + case 'Set': + case 'SetAccessor': + case 'SetIndexedPropertyHandler': + case 'SetNamedPropertyHandler': + case 'SetPrototype': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); + default: + } + + /* Automatic ToLocalChecked(), take it or leave it */ + switch (arguments[groups[12][0]]) { + case 'Date': + case 'String': + case 'RegExp': + return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); + default: + } + + /* NanEquals is now required for uniformity */ + if (arguments[groups[13][0]] === 'Equals') { + return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); + } + + /* use method on replacement class instead */ + if (arguments[groups[14][0]] === 'NanAssignPersistent') { + return [arguments[groups[14][0] + 1], '.Reset('].join(''); + } + + /* args --> info */ + if (arguments[groups[15][0]] === 'args') { + return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); + } + + /* ObjectWrap --> NanObjectWrap */ + if (arguments[groups[16][0]] === 'ObjectWrap') { + return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); + } + + /* Persistent --> NanPersistent */ + if (arguments[groups[17][0]] === 'Persistent') { + return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); + } + + /* This should not happen. A switch is probably missing a case if it does. */ + throw 'Unhandled match: ' + arguments[0]; +} + +/* reads a file, runs replacement and writes it back */ +function processFile(file) { + fs.readFile(file, {encoding: 'utf8'}, function (err, data) { + if (err) { + throw err; + } + + /* run replacement twice, might need more runs */ + fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { + if (err) { + throw err; + } + }); + }); +} + +/* process file names from command line and process the identified files */ +for (i = 2, length = process.argv.length; i < length; i++) { + glob(process.argv[i], function (err, matches) { + if (err) { + throw err; + } + matches.forEach(processFile); + }); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f07e4b8256dd136943943b575776971c36c25e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/README.md @@ -0,0 +1,14 @@ +1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, +false positives and missed opportunities. The input files are rewritten in place. Make sure that +you have backups. You will have to manually review the changes afterwards and do some touchups. + +```sh +$ tools/1to2.js + + Usage: 1to2 [options] <file ...> + + Options: + + -h, --help output usage information + -V, --version output the version number +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2dcdd789394965b8150ff96ead49f1a6ac9caf6a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/nan/tools/package.json @@ -0,0 +1,19 @@ +{ + "name": "1to2", + "version": "1.0.0", + "description": "NAN 1 -> 2 Migration Script", + "main": "1to2.js", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "contributors": [ + "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)", + "Mathias Küsel (https://github.com/mathiask88/)" + ], + "dependencies": { + "glob": "~5.0.10", + "commander": "~2.8.1" + }, + "license": "MIT" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.airtap.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.airtap.yml new file mode 100644 index 0000000000000000000000000000000000000000..3417780255e8e2206743100e52bcbb5b66408714 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.airtap.yml @@ -0,0 +1,15 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: microsoftedge + version: latest + - name: ie + version: latest + - name: iphone + version: latest diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..f25afbd2f19c75deaefccf85e63a5181a1fb3e54 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - lts/* +addons: + sauce_connect: true + hosts: + - airtap.local +env: + global: + - secure: i51rE9rZGHbcZWlL58j3H1qtL23OIV2r0X4TcQKNI3pw2mubdHFJmfPNNO19ItfReu8wwQMxOehKamwaNvqMiKWyHfn/QcThFQysqzgGZ6AgnUbYx9od6XFNDeWd1sVBf7QBAL07y7KWlYGWCwFwWjabSVySzQhEBdisPcskfkI= + - secure: BKq6/5z9LK3KDkTjs7BGeBZ1KsWgz+MsAXZ4P64NSeVGFaBdXU45+ww1mwxXFt5l22/mhyOQZfebQl+kGVqRSZ+DEgQeCymkNZ6CD8c6w6cLuOJXiXwuu/cDM2DD0tfGeu2YZC7yEikP7BqEFwH3D324rRzSGLF2RSAAwkOI7bE= diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35761fb5f8bbb0728d94496f174dd4c8d4c9e850 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/README.md @@ -0,0 +1,85 @@ +# typedarray-to-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/typedarray-to-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/typedarray-to-buffer +[npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg +[npm-url]: https://npmjs.org/package/typedarray-to-buffer +[downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg +[downloads-url]: https://npmjs.org/package/typedarray-to-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg +[saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer + +Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or +[browserify](http://browserify.org/) and you're working with lots of binary data. + +Unfortunately, sometimes the browser or someone else's API gives you a typed array like +`Uint8Array` to work with and you need to convert it to a `Buffer`. What do you do? + +Of course: `Buffer.from(uint8array)` + +But, alas, every time you do `Buffer.from(uint8array)` **the entire array gets copied**. +The `Buffer` constructor does a copy; this is +defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module +matches the node API exactly. + +So, how can we avoid this expensive copy in +[performance critical applications](https://github.com/feross/buffer/issues/22)? + +***Simply use this module, of course!*** + +If you have an `ArrayBuffer`, you don't need this module, because +`Buffer.from(arrayBuffer)` +[is already efficient](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length). + +## install + +```bash +npm install typedarray-to-buffer +``` + +## usage + +To convert a typed array to a `Buffer` **without a copy**, do this: + +```js +var toBuffer = require('typedarray-to-buffer') + +var arr = new Uint8Array([1, 2, 3]) +arr = toBuffer(arr) + +// arr is a buffer now! + +arr.toString() // '\u0001\u0002\u0003' +arr.readUInt16BE(0) // 258 +``` + +## how it works + +If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you +pass in with the `Buffer` methods and return it. See [how does Buffer +work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation +works. + +This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This +respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other +words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will +contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't +require a copy. + +If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` +object, copy the data into it, and return it. There's no simple performance optimization +we can do for old browsers. Oh well. + +If this module is used in node, then it will just call `Buffer.from`. This is just for +the convenience of modules that work in both node and the browser. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5fa394dd201d2e717aced4aea51c7a9d81c61361 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/index.js @@ -0,0 +1,25 @@ +/** + * Convert a typed array to a Buffer without a copy + * + * Author: Feross Aboukhadijeh <https://feross.org> + * License: MIT + * + * `npm install typedarray-to-buffer` + */ + +var isTypedArray = require('is-typedarray').strict + +module.exports = function typedarrayToBuffer (arr) { + if (isTypedArray(arr)) { + // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer + var buf = Buffer.from(arr.buffer) + if (arr.byteLength !== arr.buffer.byteLength) { + // Respect the "view", i.e. byteOffset and byteLength, without doing a copy + buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength) + } + return buf + } else { + // Pass through all other types to `Buffer.from` + return Buffer.from(arr) + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..66e08c6b7d35c0829dcd2636ebcd6b146552f4e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/package.json @@ -0,0 +1,75 @@ +{ + "_from": "typedarray-to-buffer@^3.1.2", + "_id": "typedarray-to-buffer@3.1.5", + "_inBundle": false, + "_integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "_location": "/typedarray-to-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "typedarray-to-buffer@^3.1.2", + "name": "typedarray-to-buffer", + "escapedName": "typedarray-to-buffer", + "rawSpec": "^3.1.2", + "saveSpec": null, + "fetchSpec": "^3.1.2" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "_shasum": "a97ee7a9ff42691b9f783ff1bc5112fe3fca9080", + "_spec": "typedarray-to-buffer@^3.1.2", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org/" + }, + "bugs": { + "url": "https://github.com/feross/typedarray-to-buffer/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-typedarray": "^1.0.0" + }, + "deprecated": false, + "description": "Convert a typed array to a Buffer without a copy", + "devDependencies": { + "airtap": "0.0.4", + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "http://feross.org", + "keywords": [ + "buffer", + "typed array", + "convert", + "no copy", + "uint8array", + "uint16array", + "uint32array", + "int16array", + "int32array", + "float32array", + "float64array", + "browser", + "arraybuffer", + "dataview" + ], + "license": "MIT", + "main": "index.js", + "name": "typedarray-to-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/typedarray-to-buffer.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "version": "3.1.5" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/test/basic.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/test/basic.js new file mode 100644 index 0000000000000000000000000000000000000000..352109682f5c121df3811f202b255d2c9a47294a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/typedarray-to-buffer/test/basic.js @@ -0,0 +1,50 @@ +var test = require('tape') +var toBuffer = require('../') + +test('convert to buffer from Uint8Array', function (t) { + if (typeof Uint8Array !== 'undefined') { + var arr = new Uint8Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 2, 3]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt8(0), 1) + t.equal(arr.readUInt8(1), 2) + t.equal(arr.readUInt8(2), 3) + } else { + t.pass('browser lacks Uint8Array support, skip test') + } + t.end() +}) + +test('convert to buffer from another arrayview type (Uint32Array)', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 1) + t.equal(arr.readUInt32LE(4), 2) + t.equal(arr.readUInt32LE(8), 3) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks Uint32Array support, skip test') + } + t.end() +}) + +test('convert to buffer from ArrayBuffer', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]).subarray(1, 2) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([2, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 2) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks ArrayBuffer support, skip test') + } + t.end() +}) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/.jshintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..98d8766cb3b3b0fa50480e0e2a8e98e8f351b03b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/.jshintrc @@ -0,0 +1,88 @@ +{ + // JSHint Default Configuration File (as on JSHint website) + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : false, // true: Identifiers must be in camelCase + "curly" : true, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc. + "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty() + "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "latedef" : "nofunc", // true: Require variables/functions to be defined before being used + "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : true, // true: Prohibit use of empty blocks + "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters. + "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : "single", // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : "vars", // vars: Require all defined variables be used, ignore function params + "strict" : false, // true: Requires all functions run in ES5 Strict Mode + "maxparams" : false, // {int} Max number of formal params allowed per function + "maxdepth" : false, // {int} Max depth of nested blocks (within functions) + "maxstatements" : false, // {int} Max number statements per function + "maxcomplexity" : false, // {int} Max cyclomatic complexity per function + "maxlen" : false, // {int} Max number of characters per line + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) + "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements + "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "multistr" : false, // true: Tolerate multi-line strings + "noyield" : false, // true: Tolerate generator functions with no yield statement in them. + "notypeof" : false, // true: Tolerate invalid typeof operator values + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + + // Environments + "browser" : true, // Web Browser (window, document, etc) + "browserify" : true, // Browserify (node.js code in the browser) + "couch" : false, // CouchDB + "devel" : true, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jasmine" : false, // Jasmine + "jquery" : false, // jQuery + "mocha" : false, // Mocha + "mootools" : false, // MooTools + "node" : true, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "prototypejs" : false, // Prototype and Scriptaculous + "qunit" : false, // QUnit + "rhino" : false, // Rhino + "shelljs" : false, // ShellJS + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + + // Custom Globals + "globals" : { // additional predefined global variables + "WebSocket": true + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..33655715134a70265d832351fdca360f68aca7d8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/CHANGELOG.md @@ -0,0 +1,225 @@ +Changelog +========= + +Version 1.0.25 +-------------- +*Released 2017-10-18* + +* Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x +* [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml) +* [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil)) +* [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit)) +* [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki)) +* [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker)) + + +Version 1.0.24 +-------------- +*Released 2016-12-28* + +* Fixed a bug when using native keepalive on Node >= 6.0. (Thanks, [@prossin](https://github.com/prossin)) +* Upgrading outdated dependencies + +Version 1.0.23 +-------------- +*Released 2016-05-18* + +* Official support for Node 6.x +* Updating dependencies. Specifically, updating nan to ^2.3.3 + +Version 1.0.22 +-------------- +*Released 2015-09-28* + +* Updating to work with nan 2.x + +Version 1.0.21 +-------------- +*Released 2015-07-22* + +* Incremented and re-published to work around an aborted npm publish of v1.0.20. + +Version 1.0.20 +-------------- +*Released 2015-07-22* + +* Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!) +* Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!) + +Version 1.0.19 +-------------- +*Released 2015-05-28* + +* Updated to nan v1.8.x (tested with v1.8.4) +* Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/). + + +Version 1.0.18 +-------------- +*Released 2015-03-19* + +* Resolves [issue #195](https://github.com/theturtle32/WebSocket-Node/pull/179) - passing number to connection.send() causes crash +* [Added close code/reason arguments to W3CWebSocket#close()](https://github.com/theturtle32/WebSocket-Node/issues/184) + + +Version 1.0.17 +-------------- +*Released 2015-01-17* + +* Resolves [issue #179](https://github.com/theturtle32/WebSocket-Node/pull/179) - Allow toBuffer to work with empty data + + +Version 1.0.16 +-------------- +*Released 2015-01-16* + +* Resolves [issue #178](https://github.com/theturtle32/WebSocket-Node/issues/178) - Ping Frames with no data + + +Version 1.0.15 +-------------- +*Released 2015-01-13* + +* Resolves [issue #177](https://github.com/theturtle32/WebSocket-Node/issues/177) - WebSocketClient ignores options unless it has a tlsOptions property + + +Version 1.0.14 +-------------- +*Released 2014-12-03* + +* Resolves [issue #173](https://github.com/theturtle32/WebSocket-Node/issues/173) - To allow the W3CWebSocket interface to accept an optional non-standard configuration object as its third parameter, which will be ignored when running in a browser context. + + +Version 1.0.13 +-------------- +*Released 2014-11-29* + +* Fixes [issue #171](https://github.com/theturtle32/WebSocket-Node/issues/171) - Code to prevent calling req.accept/req.reject multiple times breaks sanity checks in req.accept + + +Version 1.0.12 +-------------- +*Released 2014-11-28* + +* Fixes [issue #170](https://github.com/theturtle32/WebSocket-Node/issues/170) - Non-native XOR implementation broken after making JSHint happy + + +Version 1.0.11 +-------------- +*Released 2014-11-25* + +* Fixes some undefined behavior surrounding closing WebSocket connections and more reliably handles edge cases. +* Adds an implementation of the W3C WebSocket API for browsers to facilitate sharing code between client and server via browserify. (Thanks, [@ibc](https://github.com/ibc)!) +* `WebSocketConnection.prototype.close` now accepts optional `reasonCode` and `description` parameters. +* Calling `accept` or `reject` more than once on a `WebSocketRequest` will now throw an error. [Issue #149](https://github.com/theturtle32/WebSocket-Node/issues/149) +* Handling connections dropped by client before accepted by server [Issue #167](https://github.com/theturtle32/WebSocket-Node/issues/167) +* Integrating Gulp and JSHint (Thanks, [@ibc](https://github.com/ibc)!) +* Starting to add individual unit tests (using substack's [tape](github.com/substack/tape) and [faucet](github.com/substack/faucet)) + + +Version 1.0.10 +-------------- +*Released 2014-10-22* + +* Fixed Issue [#146](https://github.com/theturtle32/WebSocket-Node/issues/146) that was causing WebSocketClient to throw errors when instantiated if passed `tlsOptions`. + +Version 1.0.9 +------------- +*Released 2014-10-20* + +* Fixing an insidious corner-case bug that prevented `WebSocketConnection` from firing the `close` event in certain cases when there was an error on the underlying `Socket`, leading to connections sticking around forever, stuck erroneously in the `connected` state. These "ghost" connections would cause an error event when trying to write to them. +* Removed deprecated `websocketVersion` property. Use `webSocketVersion` instead (case difference). +* Allowing user to specify all properties for `tlsOptions` in WebSocketClient, not just a few whitelisted properties. This keeps us from having to constantly add new config properties for new versions of Node. (Thanks, [jesusprubio](https://github.com/jesusprubio)) +* Removing support for Node 0.4.x and 0.6.x. +* Adding `fuzzingclient.json` spec file for the Autobahn Test Suite. +* Now more fairly emitting `message` events from the `WebSocketConnection`. Previously, all buffered frames for a connection would be processed and all `message` events emitted before moving on to processing the next connection with available data. Now We process one frame per connection (most of the time) in a more fair round-robin fashion. +* Now correctly calling the `EventEmitter` superclass constructor during class instance initialization. +* `WebSocketClient.prototype.connect` now accepts the empty string (`''`) to mean "no subprotocol requested." Previously either `null` or an empty array (`[]`) was required. +* Fixing a `TypeError` bug in `WebSocketRouter` (Thanks, [a0000778](https://github.com/a0000778)) +* Fixing a potential race condition when attaching event listeners to the underlying `Socket`. (Thanks [RichardBsolut](https://github.com/RichardBsolut)) +* `WebSocketClient` now accepts an optional options hash to be passed to `(http|https).request`. (Thanks [mildred](https://github.com/mildred) and [aus](https://github.com/aus)) This enables the following new abilities, amongst others: + * Use WebSocket-Node from behind HTTP/HTTPS proxy servers using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar. + * Specify the local port and local address to bind the outgoing request socket to. +* Adding option to ignore `X-Forwarded-For` headers when accepting connections from untrusted clients. +* Adding ability to mount a `WebSocketServer` instance to an arbitrary number of Node http/https servers. +* Adding browser shim so Browserify won't blow up when trying to package up code that uses WebSocket-Node. The shim is a no-op, it ***does not implement a wrapper*** providing the WebSocket-Node API in the browser. +* Incorporating upstream enhancements for the native C++ UTF-8 validation and xor masking functions. (Thanks [einaros](https://github.com/einaros) and [kkoopa](https://github.com/kkoopa)) + + +Version 1.0.8 +------------- +*Released 2012-12-26* + +* Fixed remaining naming inconsistency of "websocketVersion" as opposed to "webSocketVersion" throughout the code, and added deprecation warnings for use of the old casing throughout. +* Fixed an issue with our case-insensitive handling of WebSocket subprotocols. Clients that requested a mixed-case subprotocol would end up failing the connection when the server accepted the connection, returning a lower-case version of the subprotocol name. Now we return the subprotocol name in the exact casing that was requested by the client, while still maintaining the case-insensitive verification logic for convenience and practicality. +* Making sure that any socket-level activity timeout that may have been set on a TCP socket is removed when initializing a connection. +* Added support for native TCP Keep-Alive instead of using the WebSocket ping/pong packets to serve that function. +* Fixed cookie parsing to be compliant with RFC 2109 + +Version 1.0.7 +------------- +*Released 2012-08-12* + +* ***Native modules are now optional!*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code. +* Reduced Node.JS version requirement back to v0.6.10 + +Version 1.0.6 +------------- +*Released 2012-05-22* + +* Now requires Node v0.6.13 since that's the first version that I can manage to successfully build the native UTF-8 validator with node-gyp through npm. + +Version 1.0.5 +------------- +*Released 2012-05-21* + +* Fixes the issues that users were having building the native UTF-8 validator on Windows platforms. Special Thanks to: + * [zerodivisi0n](https://github.com/zerodivisi0n) + * [andreasbotsikas](https://github.com/andreasbotsikas) +* Fixed accidental global variable usage (Thanks, [hakobera](https://github.com/hakobera)!) +* Added callbacks to the send* methods that provide notification of messages being sent on the wire and any socket errors that may occur when sending a message. (Thanks, [zerodivisi0n](https://github.com/zerodivisi0n)!) +* Added option to disable logging in the echo-server in the test folder (Thanks, [oberstet](https://github.com/oberstet)!) + + +Version 1.0.4 +------------- +*Released 2011-12-18* + +* Now validates that incoming UTF-8 messages do, in fact, contain valid UTF-8 data. The connection is dropped with prejudice if invalid data is received. This strict behavior conforms to the WebSocket RFC and is verified by the Autobahn Test Suite. This is accomplished in a performant way by using a native C++ Node module created by [einaros](https://github.com/einaros). +* Updated handling of connection closure to pass more of the Autobahn Test Suite. + +Version 1.0.3 +------------- +*Released 2011-12-18* + +* Substantial speed increase (~150% on my machine, depending on the circumstances) due to an optimization in FastBufferList.js that drastically reduces the number of memory alloctions and buffer copying. ([kazuyukitanimura](https://github.com/kazuyukitanimura)) + + +Version 1.0.2 +------------- +*Released 2011-11-28* + +* Fixing whiteboard example to work under Node 0.6.x ([theturtle32](https://github.com/theturtle32)) +* Now correctly emitting a `close` event with a 1006 error code if there is a TCP error while writing to the socket during the handshake. ([theturtle32](https://github.com/theturtle32)) +* Catching errors when writing to the TCP socket during the handshake. ([justoneplanet](https://github.com/justoneplanet)) +* No longer outputting console.warn messages when there is an error writing to the TCP socket ([justoneplanet](https://github.com/justoneplanet)) +* Fixing some formatting errors, commas, semicolons, etc. ([kaisellgren](https://github.com/kaisellgren)) + + +Version 1.0.1 +------------- +*Released 2011-11-21* + +* Now works with Node 0.6.2 as well as 0.4.12 +* Support TLS in WebSocketClient +* Added support for setting and reading cookies +* Added WebSocketServer.prototype.broadcast(data) convenience method +* Added `resourceURL` property to WebSocketRequest objects. It is a Node URL object with the `resource` and any query string params already parsed. +* The WebSocket request router no longer includes the entire query string when trying to match the path name of the request. +* WebSocketRouterRequest objects now include all the properties and events of WebSocketRequest objects. +* Removed more console.log statements. Please rely on the various events emitted to be notified of error conditions. I decided that it is not a library's place to spew information to the console. +* Renamed the `websocketVersion` property to `webSocketVersion` throughout the code to fix inconsistent capitalization. `websocketVersion` has been kept for compatibility but is deprecated and may be removed in the future. +* Now outputting the sanitized version of custom header names rather than the raw value. This prevents invalid HTTP from being put onto the wire if given an illegal header name. + + +I decided it's time to start maintaining a changelog now, starting with version 1.0.1. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..430d42bbea592e3c130eda0a07a7e1082b96ba73 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/LICENSE @@ -0,0 +1,177 @@ + + 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 diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..39ff64556ce65f5fe7749e2f07c9476e281a0663 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/Makefile @@ -0,0 +1,11 @@ +all: + node-gyp configure build + +clean: + node-gyp clean + +autobahn: + @NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000 + +autobahn-server: + @NODE_PATH=lib node test/echo-server.js diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df9584f7d536f63fe3276b5845fad700ffa46e25 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/README.md @@ -0,0 +1,291 @@ +WebSocket Client & Server Implementation for Node +================================================= + +[](http://badge.fury.io/js/websocket) + +[](https://www.npmjs.com/package/websocket) + +[](https://nodei.co/npm/websocket/) + +[](https://nodei.co/npm/websocket/) + +[ ](https://codeship.com/projects/61106) + +Overview +-------- +This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder. + +For a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/theturtle32/AS3WebSocket) project. + + +Documentation +============= + +[You can read the full API documentation in the docs folder.](docs/index.md) + + +Changelog +--------- + +***Current Version: 1.0.25*** — Released 2017-10-18 + +* Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x +* [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml) +* [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil)) +* [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit)) +* [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki)) +* [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker)) + +[View the full changelog](CHANGELOG.md) + +Browser Support +--------------- + +All current browsers are fully supported. + +* Firefox 7-9 (Old) (Protocol Version 8) +* Firefox 10+ (Protocol Version 13) +* Chrome 14,15 (Old) (Protocol Version 8) +* Chrome 16+ (Protocol Version 13) +* Internet Explorer 10+ (Protocol Version 13) +* Safari 6+ (Protocol Version 13) + +***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets*** + +***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579*** + +Benchmarks +---------- +There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4. + +Autobahn Tests +-------------- +The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability. + +- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/) + +Notes +----- +This library has been used in production on [worlize.com](https://www.worlize.com) since April 2011 and seems to be stable. Your mileage may vary. + +**Tested with the following node versions:** + +- 6.2.0 +- 5.11.1 +- 4.4.4 +- 0.10.45 + +It may work in earlier or later versions but I'm not actively testing it outside of the listed versions. YMMV. + +Installation +------------ + +A few users have reported difficulties building the native extensions without first manually installing node-gyp. If you have trouble building the native extensions, make sure you've got a C++ compiler, and have done `npm install -g node-gyp` first. + +Native extensions are optional, however, and WebSocket-Node will work even if the extensions cannot be compiled. + +In your project root: + + $ npm install websocket + +Then in your code: + +```javascript +var WebSocketServer = require('websocket').server; +var WebSocketClient = require('websocket').client; +var WebSocketFrame = require('websocket').frame; +var WebSocketRouter = require('websocket').router; +var W3CWebSocket = require('websocket').w3cwebsocket; +``` + +Note for Windows Users +---------------------- +Because there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module: + +- [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express) +- [Python 2.7](http://www.python.org/download/) (NOT Python 3.x) + + +Current Features: +----------------- +- Licensed under the Apache License, Version 2.0 +- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake +- Can handle/aggregate received fragmented messages +- Can fragment outgoing messages +- Router to mount multiple applications to various path and protocol combinations +- TLS supported for outbound connections via WebSocketClient +- TLS supported for server connections (use https.createServer instead of http.createServer) + - Thanks to [pors](https://github.com/pors) for confirming this! +- Cookie setting and parsing +- Tunable settings + - Max Receivable Frame Size + - Max Aggregate ReceivedMessage Size + - Whether to fragment outgoing messages + - Fragmentation chunk size for outgoing messages + - Whether to automatically send ping frames for the purposes of keepalive + - Keep-alive ping interval + - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly) + - How long to wait after sending a close frame for acknowledgment before closing the socket. +- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class). + + +Known Issues/Missing Features: +------------------------------ +- No API for user-provided protocol extensions. + + +Usage Examples +============== + +Server Example +-------------- + +Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary. + +```javascript +#!/usr/bin/env node +var WebSocketServer = require('websocket').server; +var http = require('http'); + +var server = http.createServer(function(request, response) { + console.log((new Date()) + ' Received request for ' + request.url); + response.writeHead(404); + response.end(); +}); +server.listen(8080, function() { + console.log((new Date()) + ' Server is listening on port 8080'); +}); + +wsServer = new WebSocketServer({ + httpServer: server, + // You should not use autoAcceptConnections for production + // applications, as it defeats all standard cross-origin protection + // facilities built into the protocol and the browser. You should + // *always* verify the connection's origin and decide whether or not + // to accept it. + autoAcceptConnections: false +}); + +function originIsAllowed(origin) { + // put logic here to detect whether the specified origin is allowed. + return true; +} + +wsServer.on('request', function(request) { + if (!originIsAllowed(request.origin)) { + // Make sure we only accept requests from an allowed origin + request.reject(); + console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); + return; + } + + var connection = request.accept('echo-protocol', request.origin); + console.log((new Date()) + ' Connection accepted.'); + connection.on('message', function(message) { + if (message.type === 'utf8') { + console.log('Received Message: ' + message.utf8Data); + connection.sendUTF(message.utf8Data); + } + else if (message.type === 'binary') { + console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); + connection.sendBytes(message.binaryData); + } + }); + connection.on('close', function(reasonCode, description) { + console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); + }); +}); +``` + +Client Example +-------------- + +This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number. + +*This code demonstrates a client in Node.js, not in the browser* + +```javascript +#!/usr/bin/env node +var WebSocketClient = require('websocket').client; + +var client = new WebSocketClient(); + +client.on('connectFailed', function(error) { + console.log('Connect Error: ' + error.toString()); +}); + +client.on('connect', function(connection) { + console.log('WebSocket Client Connected'); + connection.on('error', function(error) { + console.log("Connection Error: " + error.toString()); + }); + connection.on('close', function() { + console.log('echo-protocol Connection Closed'); + }); + connection.on('message', function(message) { + if (message.type === 'utf8') { + console.log("Received: '" + message.utf8Data + "'"); + } + }); + + function sendNumber() { + if (connection.connected) { + var number = Math.round(Math.random() * 0xFFFFFF); + connection.sendUTF(number.toString()); + setTimeout(sendNumber, 1000); + } + } + sendNumber(); +}); + +client.connect('ws://localhost:8080/', 'echo-protocol'); +``` + +Client Example using the *W3C WebSocket API* +-------------------------------------------- + +Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/). + +```javascript +var W3CWebSocket = require('websocket').w3cwebsocket; + +var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); + +client.onerror = function() { + console.log('Connection Error'); +}; + +client.onopen = function() { + console.log('WebSocket Client Connected'); + + function sendNumber() { + if (client.readyState === client.OPEN) { + var number = Math.round(Math.random() * 0xFFFFFF); + client.send(number.toString()); + setTimeout(sendNumber, 1000); + } + } + sendNumber(); +}; + +client.onclose = function() { + console.log('echo-protocol Client Closed'); +}; + +client.onmessage = function(e) { + if (typeof e.data === 'string') { + console.log("Received: '" + e.data + "'"); + } +}; +``` + +Request Router Example +---------------------- + +For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder. + + +Resources +--------- + +A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/binding.gyp b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/binding.gyp new file mode 100644 index 0000000000000000000000000000000000000000..77b2ed52ed5bd4ff255a7be51a6496b76d59f0f4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/binding.gyp @@ -0,0 +1,18 @@ +{ + 'targets': [ + { + 'target_name': 'validation', + 'include_dirs': ["<!(node -e \"require('nan')\")"], + 'cflags!': [ '-O3' ], + 'cflags': [ '-O2' ], + 'sources': [ 'src/validation.cc' ] + }, + { + 'target_name': 'bufferutil', + 'include_dirs': ["<!(node -e \"require('nan')\")"], + 'cflags!': [ '-O3' ], + 'cflags': [ '-O2' ], + 'sources': [ 'src/bufferutil.cc' ] + } + ] +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..72814773243119c9db5f3439e5b5cf285a20eb7c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/Makefile @@ -0,0 +1,320 @@ +# We borrow heavily from the kernel build setup, though we are simpler since +# we don't have Kconfig tweaking settings on us. + +# The implicit make rules have it looking for RCS files, among other things. +# We instead explicitly write all the rules we care about. +# It's even quicker (saves ~200ms) to pass -r on the command line. +MAKEFLAGS=-r + +# The source directory tree. +srcdir := .. +abs_srcdir := $(abspath $(srcdir)) + +# The name of the builddir. +builddir_name ?= . + +# The V=1 flag on command line makes us verbosely print command lines. +ifdef V + quiet= +else + quiet=quiet_ +endif + +# Specify BUILDTYPE=Release on the command line for a release build. +BUILDTYPE ?= Release + +# Directory all our build output goes into. +# Note that this must be two directories beneath src/ for unit tests to pass, +# as they reach into the src/ directory for data with relative paths. +builddir ?= $(builddir_name)/$(BUILDTYPE) +abs_builddir := $(abspath $(builddir)) +depsdir := $(builddir)/.deps + +# Object output directory. +obj := $(builddir)/obj +abs_obj := $(abspath $(obj)) + +# We build up a list of every single one of the targets so we can slurp in the +# generated dependency rule Makefiles in one pass. +all_deps := + + + +CC.target ?= $(CC) +CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) +CXX.target ?= $(CXX) +CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) +LINK.target ?= $(LINK) +LDFLAGS.target ?= $(LDFLAGS) +AR.target ?= $(AR) + +# C++ apps need to be linked with g++. +LINK ?= $(CXX.target) + +# TODO(evan): move all cross-compilation logic to gyp-time so we don't need +# to replicate this environment fallback in make as well. +CC.host ?= gcc +CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) +CXX.host ?= g++ +CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) +LINK.host ?= $(CXX.host) +LDFLAGS.host ?= +AR.host ?= ar + +# Define a dir function that can handle spaces. +# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions +# "leading spaces cannot appear in the text of the first argument as written. +# These characters can be put into the argument value by variable substitution." +empty := +space := $(empty) $(empty) + +# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces +replace_spaces = $(subst $(space),?,$1) +unreplace_spaces = $(subst ?,$(space),$1) +dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) + +# Flags to make gcc output dependency info. Note that you need to be +# careful here to use the flags that ccache and distcc can understand. +# We write to a dep file on the side first and then rename at the end +# so we can't end up with a broken dep file. +depfile = $(depsdir)/$(call replace_spaces,$@).d +DEPFLAGS = -MMD -MF $(depfile).raw + +# We have to fixup the deps output in a few ways. +# (1) the file output should mention the proper .o file. +# ccache or distcc lose the path to the target, so we convert a rule of +# the form: +# foobar.o: DEP1 DEP2 +# into +# path/to/foobar.o: DEP1 DEP2 +# (2) we want missing files not to cause us to fail to build. +# We want to rewrite +# foobar.o: DEP1 DEP2 \ +# DEP3 +# to +# DEP1: +# DEP2: +# DEP3: +# so if the files are missing, they're just considered phony rules. +# We have to do some pretty insane escaping to get those backslashes +# and dollar signs past make, the shell, and sed at the same time. +# Doesn't work with spaces, but that's fine: .d files have spaces in +# their names replaced with other characters. +define fixup_dep +# The depfile may not exist if the input file didn't have any #includes. +touch $(depfile).raw +# Fixup path as in (1). +sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_objc = CXX($(TOOLSET)) $@ +cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< + +quiet_cmd_objcxx = CXX($(TOOLSET)) $@ +cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# Commands for precompiled header files. +quiet_cmd_pch_c = CXX($(TOOLSET)) $@ +cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ +cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_m = CXX($(TOOLSET)) $@ +cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< +quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ +cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# gyp-mac-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_mac_tool = MACTOOL $(4) $< +cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" + +quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ +cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) + +quiet_cmd_infoplist = INFOPLIST $@ +cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = LIBTOOL-STATIC $@ +cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) + +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 2,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/bufferutil.target.mk b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/bufferutil.target.mk new file mode 100644 index 0000000000000000000000000000000000000000..c514c08ff522986fcd593a1d17ddf7f0f5731d3e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/bufferutil.target.mk @@ -0,0 +1,17 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := bufferutil +DEFS_Debug := \ + '-DNODE_GYP_MODULE_NAME=bufferutil' \ + '-DUSING_UV_SHARED=1' \ + '-DUSING_V8_SHARED=1' \ + '-DV8_DEPRECATION_WARNINGS=1' \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' \ + '-DV8_ENABLE_CHECKS' + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/config.gypi b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/config.gypi new file mode 100644 index 0000000000000000000000000000000000000000..2b03da969939a0fec55a116113b81a9fcd593268 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/config.gypi @@ -0,0 +1,184 @@ +# Do not edit. File was generated by node-gyp's "configure" step +{ + "target_defaults": { + "cflags": [], + "default_configuration": "Release", + "defines": [], + "include_dirs": [], + "libraries": [] + }, + "variables": { + "asan": 0, + "coverage": "false", + "debug_devtools": "node", + "debug_http2": "false", + "debug_nghttp2": "false", + "force_dynamic_crt": 0, + "host_arch": "x64", + "icu_data_file": "icudt60l.dat", + "icu_data_in": "../../deps/icu-small/source/data/in/icudt60l.dat", + "icu_endianness": "l", + "icu_gyp_path": "tools/icu/icu-generic.gyp", + "icu_locales": "en,root", + "icu_path": "deps/icu-small", + "icu_small": "true", + "icu_ver_major": "60", + "llvm_version": 0, + "node_byteorder": "little", + "node_enable_d8": "false", + "node_enable_v8_vtunejit": "false", + "node_install_npm": "true", + "node_module_version": 57, + "node_no_browser_globals": "false", + "node_prefix": "/usr/local", + "node_release_urlbase": "https://nodejs.org/download/release/", + "node_shared": "false", + "node_shared_cares": "false", + "node_shared_http_parser": "false", + "node_shared_libuv": "false", + "node_shared_nghttp2": "false", + "node_shared_openssl": "false", + "node_shared_zlib": "false", + "node_tag": "", + "node_use_bundled_v8": "true", + "node_use_dtrace": "true", + "node_use_etw": "false", + "node_use_lttng": "false", + "node_use_openssl": "true", + "node_use_perfctr": "false", + "node_use_v8_platform": "true", + "node_without_node_options": "false", + "openssl_fips": "", + "openssl_no_asm": 0, + "shlib_suffix": "57.dylib", + "target_arch": "x64", + "uv_parent_path": "/deps/uv/", + "uv_use_dtrace": "true", + "v8_enable_gdbjit": 0, + "v8_enable_i18n_support": 1, + "v8_enable_inspector": 1, + "v8_no_strict_aliasing": 1, + "v8_optimized_debug": 0, + "v8_promise_internal_field_count": 1, + "v8_random_seed": 0, + "v8_trace_maps": 0, + "v8_use_snapshot": "true", + "want_separate_host_toolset": 0, + "xcode_version": "7.0", + "nodedir": "/Users/Kens/.node-gyp/8.10.0", + "standalone_static_library": 1, + "dry_run": "", + "legacy_bundling": "", + "save_dev": "", + "browser": "", + "commit_hooks": "true", + "only": "", + "viewer": "man", + "also": "", + "rollback": "true", + "usage": "", + "globalignorefile": "/usr/local/etc/npmignore", + "init_author_url": "", + "maxsockets": "50", + "shell": "/bin/bash", + "metrics_registry": "https://registry.npmjs.org/", + "parseable": "", + "shrinkwrap": "true", + "init_license": "ISC", + "timing": "", + "if_present": "", + "cache_max": "Infinity", + "init_author_email": "", + "sign_git_tag": "", + "cert": "", + "git_tag_version": "true", + "local_address": "", + "long": "", + "fetch_retries": "2", + "registry": "https://registry.npmjs.org/", + "key": "", + "message": "%s", + "versions": "", + "globalconfig": "/usr/local/etc/npmrc", + "always_auth": "", + "logs_max": "10", + "prefer_online": "", + "cache_lock_retries": "10", + "global_style": "", + "heading": "npm", + "fetch_retry_mintimeout": "10000", + "offline": "", + "read_only": "", + "searchlimit": "20", + "access": "", + "json": "", + "allow_same_version": "", + "description": "true", + "engine_strict": "", + "https_proxy": "", + "init_module": "/Users/Kens/.npm-init.js", + "userconfig": "/Users/Kens/.npmrc", + "cidr": "", + "node_version": "8.10.0", + "user": "", + "auth_type": "legacy", + "editor": "vi", + "ignore_prepublish": "", + "save": "true", + "script_shell": "", + "tag": "latest", + "global": "", + "progress": "true", + "ham_it_up": "", + "optional": "true", + "searchstaleness": "900", + "bin_links": "true", + "force": "", + "save_prod": "", + "searchopts": "", + "depth": "Infinity", + "node_gyp": "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", + "rebuild_bundle": "true", + "sso_poll_frequency": "500", + "unicode": "true", + "fetch_retry_maxtimeout": "60000", + "ca": "", + "save_prefix": "^", + "scripts_prepend_node_path": "warn-only", + "sso_type": "oauth", + "strict_ssl": "true", + "tag_version_prefix": "v", + "dev": "", + "fetch_retry_factor": "10", + "group": "20", + "save_exact": "", + "cache_lock_stale": "60000", + "prefer_offline": "", + "version": "", + "cache_min": "10", + "otp": "", + "cache": "/Users/Kens/.npm", + "searchexclude": "", + "color": "true", + "package_lock": "true", + "package_lock_only": "", + "save_optional": "", + "user_agent": "npm/5.6.0 node/v8.10.0 darwin x64", + "ignore_scripts": "", + "cache_lock_wait": "10000", + "production": "", + "save_bundle": "", + "send_metrics": "", + "init_version": "1.0.0", + "node_options": "", + "umask": "0022", + "scope": "", + "git": "git", + "init_author_name": "", + "onload_script": "", + "tmp": "/var/folders/4d/ktz4cr454210y7dr_89c40lh0000gp/T", + "unsafe_perm": "true", + "link": "", + "prefix": "/usr/local" + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/gyp-mac-tool b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/gyp-mac-tool new file mode 100644 index 0000000000000000000000000000000000000000..8ef02b0493a003a05a90aff8975351e5f18fa85b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/build/gyp-mac-tool @@ -0,0 +1,611 @@ +#!/usr/bin/env python +# Generated by gyp. Do not edit. +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions to perform Xcode-style build steps. + +These functions are executed via gyp-mac-tool when using the Makefile generator. +""" + +import fcntl +import fnmatch +import glob +import json +import os +import plistlib +import re +import shutil +import string +import subprocess +import sys +import tempfile + + +def main(args): + executor = MacTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class MacTool(object): + """This class performs all the Mac tooling steps. The methods can either be + executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like copy-info-plist to CopyInfoPlist""" + return name_string.title().replace('-', '') + + def ExecCopyBundleResource(self, source, dest, convert_to_binary): + """Copies a resource file to the bundle/Resources directory, performing any + necessary compilation on each resource.""" + extension = os.path.splitext(source)[1].lower() + if os.path.isdir(source): + # Copy tree. + # TODO(thakis): This copies file attributes like mtime, while the + # single-file branch below doesn't. This should probably be changed to + # be consistent with the single-file branch. + if os.path.exists(dest): + shutil.rmtree(dest) + shutil.copytree(source, dest) + elif extension == '.xib': + return self._CopyXIBFile(source, dest) + elif extension == '.storyboard': + return self._CopyXIBFile(source, dest) + elif extension == '.strings': + self._CopyStringsFile(source, dest, convert_to_binary) + else: + shutil.copy(source, dest) + + def _CopyXIBFile(self, source, dest): + """Compiles a XIB file with ibtool into a binary plist in the bundle.""" + + # ibtool sometimes crashes with relative paths. See crbug.com/314728. + base = os.path.dirname(os.path.realpath(__file__)) + if os.path.relpath(source): + source = os.path.join(base, source) + if os.path.relpath(dest): + dest = os.path.join(base, dest) + + args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices', + '--output-format', 'human-readable-text', '--compile', dest, source] + ibtool_section_re = re.compile(r'/\*.*\*/') + ibtool_re = re.compile(r'.*note:.*is clipping its content') + ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) + current_section_header = None + for line in ibtoolout.stdout: + if ibtool_section_re.match(line): + current_section_header = line + elif not ibtool_re.match(line): + if current_section_header: + sys.stdout.write(current_section_header) + current_section_header = None + sys.stdout.write(line) + return ibtoolout.returncode + + def _ConvertToBinary(self, dest): + subprocess.check_call([ + 'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest]) + + def _CopyStringsFile(self, source, dest, convert_to_binary): + """Copies a .strings file using iconv to reconvert the input into UTF-16.""" + input_code = self._DetectInputEncoding(source) or "UTF-8" + + # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call + # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints + # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing + # semicolon in dictionary. + # on invalid files. Do the same kind of validation. + import CoreFoundation + s = open(source, 'rb').read() + d = CoreFoundation.CFDataCreate(None, s, len(s)) + _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) + if error: + return + + fp = open(dest, 'wb') + fp.write(s.decode(input_code).encode('UTF-16')) + fp.close() + + if convert_to_binary == 'True': + self._ConvertToBinary(dest) + + def _DetectInputEncoding(self, file_name): + """Reads the first few bytes from file_name and tries to guess the text + encoding. Returns None as a guess if it can't detect it.""" + fp = open(file_name, 'rb') + try: + header = fp.read(3) + except e: + fp.close() + return None + fp.close() + if header.startswith("\xFE\xFF"): + return "UTF-16" + elif header.startswith("\xFF\xFE"): + return "UTF-16" + elif header.startswith("\xEF\xBB\xBF"): + return "UTF-8" + else: + return None + + def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): + """Copies the |source| Info.plist to the destination directory |dest|.""" + # Read the source Info.plist into memory. + fd = open(source, 'r') + lines = fd.read() + fd.close() + + # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). + plist = plistlib.readPlistFromString(lines) + if keys: + plist = dict(plist.items() + json.loads(keys[0]).items()) + lines = plistlib.writePlistToString(plist) + + # Go through all the environment variables and replace them as variables in + # the file. + IDENT_RE = re.compile(r'[/\s]') + for key in os.environ: + if key.startswith('_'): + continue + evar = '${%s}' % key + evalue = os.environ[key] + lines = string.replace(lines, evar, evalue) + + # Xcode supports various suffices on environment variables, which are + # all undocumented. :rfc1034identifier is used in the standard project + # template these days, and :identifier was used earlier. They are used to + # convert non-url characters into things that look like valid urls -- + # except that the replacement character for :identifier, '_' isn't valid + # in a URL either -- oops, hence :rfc1034identifier was born. + evar = '${%s:identifier}' % key + evalue = IDENT_RE.sub('_', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + evar = '${%s:rfc1034identifier}' % key + evalue = IDENT_RE.sub('-', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + # Remove any keys with values that haven't been replaced. + lines = lines.split('\n') + for i in range(len(lines)): + if lines[i].strip().startswith("<string>${"): + lines[i] = None + lines[i - 1] = None + lines = '\n'.join(filter(lambda x: x is not None, lines)) + + # Write out the file with variables replaced. + fd = open(dest, 'w') + fd.write(lines) + fd.close() + + # Now write out PkgInfo file now that the Info.plist file has been + # "compiled". + self._WritePkgInfo(dest) + + if convert_to_binary == 'True': + self._ConvertToBinary(dest) + + def _WritePkgInfo(self, info_plist): + """This writes the PkgInfo file from the data stored in Info.plist.""" + plist = plistlib.readPlist(info_plist) + if not plist: + return + + # Only create PkgInfo for executable types. + package_type = plist['CFBundlePackageType'] + if package_type != 'APPL': + return + + # The format of PkgInfo is eight characters, representing the bundle type + # and bundle signature, each four characters. If that is missing, four + # '?' characters are used instead. + signature_code = plist.get('CFBundleSignature', '????') + if len(signature_code) != 4: # Wrong length resets everything, too. + signature_code = '?' * 4 + + dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') + fp = open(dest, 'w') + fp.write('%s%s' % (package_type, signature_code)) + fp.close() + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + return subprocess.call(cmd_list) + + def ExecFilterLibtool(self, *cmd_list): + """Calls libtool and filters out '/path/to/libtool: file: foo.o has no + symbols'.""" + libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$') + libtool_re5 = re.compile( + r'^.*libtool: warning for library: ' + + r'.* the table of contents is empty ' + + r'\(no object file members in the library define global symbols\)$') + env = os.environ.copy() + # Ref: + # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c + # The problem with this flag is that it resets the file mtime on the file to + # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone. + env['ZERO_AR_DATE'] = '1' + libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) + _, err = libtoolout.communicate() + for line in err.splitlines(): + if not libtool_re.match(line) and not libtool_re5.match(line): + print >>sys.stderr, line + # Unconditionally touch the output .a file on the command line if present + # and the command succeeded. A bit hacky. + if not libtoolout.returncode: + for i in range(len(cmd_list) - 1): + if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'): + os.utime(cmd_list[i+1], None) + break + return libtoolout.returncode + + def ExecPackageFramework(self, framework, version): + """Takes a path to Something.framework and the Current version of that and + sets up all the symlinks.""" + # Find the name of the binary based on the part before the ".framework". + binary = os.path.basename(framework).split('.')[0] + + CURRENT = 'Current' + RESOURCES = 'Resources' + VERSIONS = 'Versions' + + if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): + # Binary-less frameworks don't seem to contain symlinks (see e.g. + # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). + return + + # Move into the framework directory to set the symlinks correctly. + pwd = os.getcwd() + os.chdir(framework) + + # Set up the Current version. + self._Relink(version, os.path.join(VERSIONS, CURRENT)) + + # Set up the root symlinks. + self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) + self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) + + # Back to where we were before! + os.chdir(pwd) + + def _Relink(self, dest, link): + """Creates a symlink to |dest| named |link|. If |link| already exists, + it is overwritten.""" + if os.path.lexists(link): + os.remove(link) + os.symlink(dest, link) + + def ExecCompileXcassets(self, keys, *inputs): + """Compiles multiple .xcassets files into a single .car file. + + This invokes 'actool' to compile all the inputs .xcassets files. The + |keys| arguments is a json-encoded dictionary of extra arguments to + pass to 'actool' when the asset catalogs contains an application icon + or a launch image. + + Note that 'actool' does not create the Assets.car file if the asset + catalogs does not contains imageset. + """ + command_line = [ + 'xcrun', 'actool', '--output-format', 'human-readable-text', + '--compress-pngs', '--notices', '--warnings', '--errors', + ] + is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ + if is_iphone_target: + platform = os.environ['CONFIGURATION'].split('-')[-1] + if platform not in ('iphoneos', 'iphonesimulator'): + platform = 'iphonesimulator' + command_line.extend([ + '--platform', platform, '--target-device', 'iphone', + '--target-device', 'ipad', '--minimum-deployment-target', + os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile', + os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']), + ]) + else: + command_line.extend([ + '--platform', 'macosx', '--target-device', 'mac', + '--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'], + '--compile', + os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']), + ]) + if keys: + keys = json.loads(keys) + for key, value in keys.iteritems(): + arg_name = '--' + key + if isinstance(value, bool): + if value: + command_line.append(arg_name) + elif isinstance(value, list): + for v in value: + command_line.append(arg_name) + command_line.append(str(v)) + else: + command_line.append(arg_name) + command_line.append(str(value)) + # Note: actool crashes if inputs path are relative, so use os.path.abspath + # to get absolute path name for inputs. + command_line.extend(map(os.path.abspath, inputs)) + subprocess.check_call(command_line) + + def ExecMergeInfoPlist(self, output, *inputs): + """Merge multiple .plist files into a single .plist file.""" + merged_plist = {} + for path in inputs: + plist = self._LoadPlistMaybeBinary(path) + self._MergePlist(merged_plist, plist) + plistlib.writePlist(merged_plist, output) + + def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning): + """Code sign a bundle. + + This function tries to code sign an iOS bundle, following the same + algorithm as Xcode: + 1. copy ResourceRules.plist from the user or the SDK into the bundle, + 2. pick the provisioning profile that best match the bundle identifier, + and copy it into the bundle as embedded.mobileprovision, + 3. copy Entitlements.plist from user or SDK next to the bundle, + 4. code sign the bundle. + """ + resource_rules_path = self._InstallResourceRules(resource_rules) + substitutions, overrides = self._InstallProvisioningProfile( + provisioning, self._GetCFBundleIdentifier()) + entitlements_path = self._InstallEntitlements( + entitlements, substitutions, overrides) + subprocess.check_call([ + 'codesign', '--force', '--sign', key, '--resource-rules', + resource_rules_path, '--entitlements', entitlements_path, + os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['FULL_PRODUCT_NAME'])]) + + def _InstallResourceRules(self, resource_rules): + """Installs ResourceRules.plist from user or SDK into the bundle. + + Args: + resource_rules: string, optional, path to the ResourceRules.plist file + to use, default to "${SDKROOT}/ResourceRules.plist" + + Returns: + Path to the copy of ResourceRules.plist into the bundle. + """ + source_path = resource_rules + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'ResourceRules.plist') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], 'ResourceRules.plist') + shutil.copy2(source_path, target_path) + return target_path + + def _InstallProvisioningProfile(self, profile, bundle_identifier): + """Installs embedded.mobileprovision into the bundle. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple containing two dictionary: variables substitutions and values + to overrides when generating the entitlements file. + """ + source_path, provisioning_data, team_id = self._FindProvisioningProfile( + profile, bundle_identifier) + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'embedded.mobileprovision') + shutil.copy2(source_path, target_path) + substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.') + return substitutions, provisioning_data['Entitlements'] + + def _FindProvisioningProfile(self, profile, bundle_identifier): + """Finds the .mobileprovision file to use for signing the bundle. + + Checks all the installed provisioning profiles (or if the user specified + the PROVISIONING_PROFILE variable, only consult it) and select the most + specific that correspond to the bundle identifier. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple of the path to the selected provisioning profile, the data of + the embedded plist in the provisioning profile and the team identifier + to use for code signing. + + Raises: + SystemExit: if no .mobileprovision can be used to sign the bundle. + """ + profiles_dir = os.path.join( + os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles') + if not os.path.isdir(profiles_dir): + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + provisioning_profiles = None + if profile: + profile_path = os.path.join(profiles_dir, profile + '.mobileprovision') + if os.path.exists(profile_path): + provisioning_profiles = [profile_path] + if not provisioning_profiles: + provisioning_profiles = glob.glob( + os.path.join(profiles_dir, '*.mobileprovision')) + valid_provisioning_profiles = {} + for profile_path in provisioning_profiles: + profile_data = self._LoadProvisioningProfile(profile_path) + app_id_pattern = profile_data.get( + 'Entitlements', {}).get('application-identifier', '') + for team_identifier in profile_data.get('TeamIdentifier', []): + app_id = '%s.%s' % (team_identifier, bundle_identifier) + if fnmatch.fnmatch(app_id, app_id_pattern): + valid_provisioning_profiles[app_id_pattern] = ( + profile_path, profile_data, team_identifier) + if not valid_provisioning_profiles: + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + # If the user has multiple provisioning profiles installed that can be + # used for ${bundle_identifier}, pick the most specific one (ie. the + # provisioning profile whose pattern is the longest). + selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) + return valid_provisioning_profiles[selected_key] + + def _LoadProvisioningProfile(self, profile_path): + """Extracts the plist embedded in a provisioning profile. + + Args: + profile_path: string, path to the .mobileprovision file + + Returns: + Content of the plist embedded in the provisioning profile as a dictionary. + """ + with tempfile.NamedTemporaryFile() as temp: + subprocess.check_call([ + 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name]) + return self._LoadPlistMaybeBinary(temp.name) + + def _MergePlist(self, merged_plist, plist): + """Merge |plist| into |merged_plist|.""" + for key, value in plist.iteritems(): + if isinstance(value, dict): + merged_value = merged_plist.get(key, {}) + if isinstance(merged_value, dict): + self._MergePlist(merged_value, value) + merged_plist[key] = merged_value + else: + merged_plist[key] = value + else: + merged_plist[key] = value + + def _LoadPlistMaybeBinary(self, plist_path): + """Loads into a memory a plist possibly encoded in binary format. + + This is a wrapper around plistlib.readPlist that tries to convert the + plist to the XML format if it can't be parsed (assuming that it is in + the binary format). + + Args: + plist_path: string, path to a plist file, in XML or binary format + + Returns: + Content of the plist as a dictionary. + """ + try: + # First, try to read the file using plistlib that only supports XML, + # and if an exception is raised, convert a temporary copy to XML and + # load that copy. + return plistlib.readPlist(plist_path) + except: + pass + with tempfile.NamedTemporaryFile() as temp: + shutil.copy2(plist_path, temp.name) + subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) + return plistlib.readPlist(temp.name) + + def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): + """Constructs a dictionary of variable substitutions for Entitlements.plist. + + Args: + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + app_identifier_prefix: string, value for AppIdentifierPrefix + + Returns: + Dictionary of substitutions to apply when generating Entitlements.plist. + """ + return { + 'CFBundleIdentifier': bundle_identifier, + 'AppIdentifierPrefix': app_identifier_prefix, + } + + def _GetCFBundleIdentifier(self): + """Extracts CFBundleIdentifier value from Info.plist in the bundle. + + Returns: + Value of CFBundleIdentifier in the Info.plist located in the bundle. + """ + info_plist_path = os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['INFOPLIST_PATH']) + info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) + return info_plist_data['CFBundleIdentifier'] + + def _InstallEntitlements(self, entitlements, substitutions, overrides): + """Generates and install the ${BundleName}.xcent entitlements file. + + Expands variables "$(variable)" pattern in the source entitlements file, + add extra entitlements defined in the .mobileprovision file and the copy + the generated plist to "${BundlePath}.xcent". + + Args: + entitlements: string, optional, path to the Entitlements.plist template + to use, defaults to "${SDKROOT}/Entitlements.plist" + substitutions: dictionary, variable substitutions + overrides: dictionary, values to add to the entitlements + + Returns: + Path to the generated entitlements file. + """ + source_path = entitlements + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['PRODUCT_NAME'] + '.xcent') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], + 'Entitlements.plist') + shutil.copy2(source_path, target_path) + data = self._LoadPlistMaybeBinary(target_path) + data = self._ExpandVariables(data, substitutions) + if overrides: + for key in overrides: + if key not in data: + data[key] = overrides[key] + plistlib.writePlist(data, target_path) + return target_path + + def _ExpandVariables(self, data, substitutions): + """Expands variables "$(variable)" in data. + + Args: + data: object, can be either string, list or dictionary + substitutions: dictionary, variable substitutions to perform + + Returns: + Copy of data where each references to "$(variable)" has been replaced + by the corresponding value found in substitutions, or left intact if + the key was not found. + """ + if isinstance(data, str): + for key, value in substitutions.iteritems(): + data = data.replace('$(%s)' % key, value) + return data + if isinstance(data, list): + return [self._ExpandVariables(v, substitutions) for v in data] + if isinstance(data, dict): + return {k: self._ExpandVariables(data[k], substitutions) for k in data} + return data + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/builderror.log b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/builderror.log new file mode 100644 index 0000000000000000000000000000000000000000..088a9a348d3382e61bac89e5210f461e70420680 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/builderror.log @@ -0,0 +1,23 @@ +xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance + +xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance + +No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'. + +No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'. + +No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'. + +gyp: No Xcode or CLT version detected! +gyp ERR! configure error +gyp ERR! stack Error: `gyp` failed with exit code: 1 +gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:336:16) +gyp ERR! stack at emitTwo (events.js:126:13) +gyp ERR! stack at ChildProcess.emit (events.js:214:7) +gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12) +gyp ERR! System Darwin 17.4.0 +gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" +gyp ERR! cwd /Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket +gyp ERR! node -v v8.10.0 +gyp ERR! node-gyp -v v3.6.2 +gyp ERR! not ok diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/gulpfile.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b515b928534ef9bdd757d0e9a445bf5f35f67c48 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/gulpfile.js @@ -0,0 +1,14 @@ +/** + * Dependencies. + */ +var gulp = require('gulp'); +var jshint = require('gulp-jshint'); + +gulp.task('lint', function() { + return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js']) + .pipe(jshint('.jshintrc')) + .pipe(jshint.reporter('jshint-stylish', {verbose: true})) + .pipe(jshint.reporter('fail')); +}); + +gulp.task('default', gulp.series('lint')); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/index.js new file mode 100644 index 0000000000000000000000000000000000000000..573969f7ce3fdaef6914a0a5da33f5d400b9fd49 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/websocket'); \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.fallback.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.fallback.js new file mode 100644 index 0000000000000000000000000000000000000000..de18bfb8102fe2e539b2b4ac60a0f5b70a6571b8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.fallback.js @@ -0,0 +1,52 @@ +/*! + * Copied from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +/* jshint -W086 */ + +module.exports.BufferUtil = { + merge: function(mergedBuffer, buffers) { + var offset = 0; + for (var i = 0, l = buffers.length; i < l; ++i) { + var buf = buffers[i]; + buf.copy(mergedBuffer, offset); + offset += buf.length; + } + }, + mask: function(source, mask, output, offset, length) { + var maskNum = mask.readUInt32LE(0, true); + var i = 0; + for (; i < length - 3; i += 4) { + var num = maskNum ^ source.readUInt32LE(i, true); + if (num < 0) { num = 4294967296 + num; } + output.writeUInt32LE(num, offset + i, true); + } + switch (length % 4) { + case 3: output[offset + i + 2] = source[i + 2] ^ mask[2]; + case 2: output[offset + i + 1] = source[i + 1] ^ mask[1]; + case 1: output[offset + i] = source[i] ^ mask[0]; + case 0: + } + }, + unmask: function(data, mask) { + var maskNum = mask.readUInt32LE(0, true); + var length = data.length; + var i = 0; + for (; i < length - 3; i += 4) { + var num = maskNum ^ data.readUInt32LE(i, true); + if (num < 0) { num = 4294967296 + num; } + data.writeUInt32LE(num, i, true); + } + switch (length % 4) { + case 3: data[i + 2] = data[i + 2] ^ mask[2]; + case 2: data[i + 1] = data[i + 1] ^ mask[1]; + case 1: data[i] = data[i] ^ mask[0]; + case 0: + } + } +}; + +/* jshint +W086 */ \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.js new file mode 100644 index 0000000000000000000000000000000000000000..fa37c8082c13465f1104f6edff2cf6bed5a9ec29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/BufferUtil.js @@ -0,0 +1,17 @@ +/*! + * Copied from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +try { + module.exports = require('../build/Release/bufferutil'); +} catch (e) { try { + module.exports = require('../build/default/bufferutil'); +} catch (e) { try { + module.exports = require('./BufferUtil.fallback'); +} catch (e) { + console.error('bufferutil.node seems to not have been built. Run npm install.'); + throw e; +}}} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Deprecation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Deprecation.js new file mode 100644 index 0000000000000000000000000000000000000000..094f160481790fa017b89e4661b6ae9566239315 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Deprecation.js @@ -0,0 +1,32 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var Deprecation = { + disableWarnings: false, + + deprecationWarningMap: { + + }, + + warn: function(deprecationName) { + if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) { + console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]); + this.deprecationWarningMap[deprecationName] = false; + } + } +}; + +module.exports = Deprecation; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.fallback.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.fallback.js new file mode 100644 index 0000000000000000000000000000000000000000..6160f888b7e3355a6298881c670f83069ea5b7e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.fallback.js @@ -0,0 +1,12 @@ +/*! + * UTF-8 Validation Fallback Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +module.exports.Validation = { + isValidUTF8: function() { + return true; + } +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.js new file mode 100644 index 0000000000000000000000000000000000000000..b4106e8d8356edd980b2c43b71b5ee1b4d4f27d3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/Validation.js @@ -0,0 +1,17 @@ +/*! + * UTF-8 Validation Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +try { + module.exports = require('../build/Release/validation'); +} catch (e) { try { + module.exports = require('../build/default/validation'); +} catch (e) { try { + module.exports = require('./Validation.fallback'); +} catch (e) { + console.error('validation.node seems not to have been built. Run npm install.'); + throw e; +}}} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/W3CWebSocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/W3CWebSocket.js new file mode 100644 index 0000000000000000000000000000000000000000..44a4ac98ebf524f7b2a02fff77c0c92935299844 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/W3CWebSocket.js @@ -0,0 +1,257 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var WebSocketClient = require('./WebSocketClient'); +var toBuffer = require('typedarray-to-buffer'); +var yaeti = require('yaeti'); + + +const CONNECTING = 0; +const OPEN = 1; +const CLOSING = 2; +const CLOSED = 3; + + +module.exports = W3CWebSocket; + + +function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig) { + // Make this an EventTarget. + yaeti.EventTarget.call(this); + + // Sanitize clientConfig. + clientConfig = clientConfig || {}; + clientConfig.assembleFragments = true; // Required in the W3C API. + + var self = this; + + this._url = url; + this._readyState = CONNECTING; + this._protocol = undefined; + this._extensions = ''; + this._bufferedAmount = 0; // Hack, always 0. + this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob. + + // The WebSocketConnection instance. + this._connection = undefined; + + // WebSocketClient instance. + this._client = new WebSocketClient(clientConfig); + + this._client.on('connect', function(connection) { + onConnect.call(self, connection); + }); + + this._client.on('connectFailed', function() { + onConnectFailed.call(self); + }); + + this._client.connect(url, protocols, origin, headers, requestOptions); +} + + +// Expose W3C read only attributes. +Object.defineProperties(W3CWebSocket.prototype, { + url: { get: function() { return this._url; } }, + readyState: { get: function() { return this._readyState; } }, + protocol: { get: function() { return this._protocol; } }, + extensions: { get: function() { return this._extensions; } }, + bufferedAmount: { get: function() { return this._bufferedAmount; } } +}); + + +// Expose W3C write/read attributes. +Object.defineProperties(W3CWebSocket.prototype, { + binaryType: { + get: function() { + return this._binaryType; + }, + set: function(type) { + // TODO: Just 'arraybuffer' supported. + if (type !== 'arraybuffer') { + throw new SyntaxError('just "arraybuffer" type allowed for "binaryType" attribute'); + } + this._binaryType = type; + } + } +}); + + +// Expose W3C readyState constants into the WebSocket instance as W3C states. +[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) { + Object.defineProperty(W3CWebSocket.prototype, property[0], { + get: function() { return property[1]; } + }); +}); + +// Also expose W3C readyState constants into the WebSocket class (not defined by the W3C, +// but there are so many libs relying on them). +[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) { + Object.defineProperty(W3CWebSocket, property[0], { + get: function() { return property[1]; } + }); +}); + + +W3CWebSocket.prototype.send = function(data) { + if (this._readyState !== OPEN) { + throw new Error('cannot call send() while not connected'); + } + + // Text. + if (typeof data === 'string' || data instanceof String) { + this._connection.sendUTF(data); + } + // Binary. + else { + // Node Buffer. + if (data instanceof Buffer) { + this._connection.sendBytes(data); + } + // If ArrayBuffer or ArrayBufferView convert it to Node Buffer. + else if (data.byteLength || data.byteLength === 0) { + data = toBuffer(data); + this._connection.sendBytes(data); + } + else { + throw new Error('unknown binary data:', data); + } + } +}; + + +W3CWebSocket.prototype.close = function(code, reason) { + switch(this._readyState) { + case CONNECTING: + // NOTE: We don't have the WebSocketConnection instance yet so no + // way to close the TCP connection. + // Artificially invoke the onConnectFailed event. + onConnectFailed.call(this); + // And close if it connects after a while. + this._client.on('connect', function(connection) { + if (code) { + connection.close(code, reason); + } else { + connection.close(); + } + }); + break; + case OPEN: + this._readyState = CLOSING; + if (code) { + this._connection.close(code, reason); + } else { + this._connection.close(); + } + break; + case CLOSING: + case CLOSED: + break; + } +}; + + +/** + * Private API. + */ + + +function createCloseEvent(code, reason) { + var event = new yaeti.Event('close'); + + event.code = code; + event.reason = reason; + event.wasClean = (typeof code === 'undefined' || code === 1000); + + return event; +} + + +function createMessageEvent(data) { + var event = new yaeti.Event('message'); + + event.data = data; + + return event; +} + + +function onConnect(connection) { + var self = this; + + this._readyState = OPEN; + this._connection = connection; + this._protocol = connection.protocol; + this._extensions = connection.extensions; + + this._connection.on('close', function(code, reason) { + onClose.call(self, code, reason); + }); + + this._connection.on('message', function(msg) { + onMessage.call(self, msg); + }); + + this.dispatchEvent(new yaeti.Event('open')); +} + + +function onConnectFailed() { + destroy.call(this); + this._readyState = CLOSED; + + try { + this.dispatchEvent(new yaeti.Event('error')); + } finally { + this.dispatchEvent(createCloseEvent(1006, 'connection failed')); + } +} + + +function onClose(code, reason) { + destroy.call(this); + this._readyState = CLOSED; + + this.dispatchEvent(createCloseEvent(code, reason || '')); +} + + +function onMessage(message) { + if (message.utf8Data) { + this.dispatchEvent(createMessageEvent(message.utf8Data)); + } + else if (message.binaryData) { + // Must convert from Node Buffer to ArrayBuffer. + // TODO: or to a Blob (which does not exist in Node!). + if (this.binaryType === 'arraybuffer') { + var buffer = message.binaryData; + var arraybuffer = new ArrayBuffer(buffer.length); + var view = new Uint8Array(arraybuffer); + for (var i=0, len=buffer.length; i<len; ++i) { + view[i] = buffer[i]; + } + this.dispatchEvent(createMessageEvent(arraybuffer)); + } + } +} + + +function destroy() { + this._client.removeAllListeners(); + if (this._connection) { + this._connection.removeAllListeners(); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketClient.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketClient.js new file mode 100644 index 0000000000000000000000000000000000000000..3b24beb8bde7ee86956e5cf7e6473fba0655de4f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketClient.js @@ -0,0 +1,348 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var utils = require('./utils'); +var extend = utils.extend; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +var http = require('http'); +var https = require('https'); +var url = require('url'); +var crypto = require('crypto'); +var WebSocketConnection = require('./WebSocketConnection'); + +var protocolSeparators = [ + '(', ')', '<', '>', '@', + ',', ';', ':', '\\', '\"', + '/', '[', ']', '?', '=', + '{', '}', ' ', String.fromCharCode(9) +]; + +function WebSocketClient(config) { + // Superclass Constructor + EventEmitter.call(this); + + // TODO: Implement extensions + + this.config = { + // 1MiB max frame size. + maxReceivedFrameSize: 0x100000, + + // 8MiB max message size, only applicable if + // assembleFragments is true + maxReceivedMessageSize: 0x800000, + + // Outgoing messages larger than fragmentationThreshold will be + // split into multiple fragments. + fragmentOutgoingMessages: true, + + // Outgoing frames are fragmented if they exceed this threshold. + // Default is 16KiB + fragmentationThreshold: 0x4000, + + // Which version of the protocol to use for this session. This + // option will be removed once the protocol is finalized by the IETF + // It is only available to ease the transition through the + // intermediate draft protocol versions. + // At present, it only affects the name of the Origin header. + webSocketVersion: 13, + + // If true, fragmented messages will be automatically assembled + // and the full message will be emitted via a 'message' event. + // If false, each frame will be emitted via a 'frame' event and + // the application will be responsible for aggregating multiple + // fragmented frames. Single-frame messages will emit a 'message' + // event in addition to the 'frame' event. + // Most users will want to leave this set to 'true' + assembleFragments: true, + + // The Nagle Algorithm makes more efficient use of network resources + // by introducing a small delay before sending small packets so that + // multiple messages can be batched together before going onto the + // wire. This however comes at the cost of latency, so the default + // is to disable it. If you don't need low latency and are streaming + // lots of small messages, you can change this to 'false' + disableNagleAlgorithm: true, + + // The number of milliseconds to wait after sending a close frame + // for an acknowledgement to come back before giving up and just + // closing the socket. + closeTimeout: 5000, + + // Options to pass to https.connect if connecting via TLS + tlsOptions: {} + }; + + if (config) { + var tlsOptions; + if (config.tlsOptions) { + tlsOptions = config.tlsOptions; + delete config.tlsOptions; + } + else { + tlsOptions = {}; + } + extend(this.config, config); + extend(this.config.tlsOptions, tlsOptions); + } + + this._req = null; + + switch (this.config.webSocketVersion) { + case 8: + case 13: + break; + default: + throw new Error('Requested webSocketVersion is not supported. Allowed values are 8 and 13.'); + } +} + +util.inherits(WebSocketClient, EventEmitter); + +WebSocketClient.prototype.connect = function(requestUrl, protocols, origin, headers, extraRequestOptions) { + var self = this; + if (typeof(protocols) === 'string') { + if (protocols.length > 0) { + protocols = [protocols]; + } + else { + protocols = []; + } + } + if (!(protocols instanceof Array)) { + protocols = []; + } + this.protocols = protocols; + this.origin = origin; + + if (typeof(requestUrl) === 'string') { + this.url = url.parse(requestUrl); + } + else { + this.url = requestUrl; // in case an already parsed url is passed in. + } + if (!this.url.protocol) { + throw new Error('You must specify a full WebSocket URL, including protocol.'); + } + if (!this.url.host) { + throw new Error('You must specify a full WebSocket URL, including hostname. Relative URLs are not supported.'); + } + + this.secure = (this.url.protocol === 'wss:'); + + // validate protocol characters: + this.protocols.forEach(function(protocol) { + for (var i=0; i < protocol.length; i ++) { + var charCode = protocol.charCodeAt(i); + var character = protocol.charAt(i); + if (charCode < 0x0021 || charCode > 0x007E || protocolSeparators.indexOf(character) !== -1) { + throw new Error('Protocol list contains invalid character "' + String.fromCharCode(charCode) + '"'); + } + } + }); + + var defaultPorts = { + 'ws:': '80', + 'wss:': '443' + }; + + if (!this.url.port) { + this.url.port = defaultPorts[this.url.protocol]; + } + + var nonce = new Buffer(16); + for (var i=0; i < 16; i++) { + nonce[i] = Math.round(Math.random()*0xFF); + } + this.base64nonce = nonce.toString('base64'); + + var hostHeaderValue = this.url.hostname; + if ((this.url.protocol === 'ws:' && this.url.port !== '80') || + (this.url.protocol === 'wss:' && this.url.port !== '443')) { + hostHeaderValue += (':' + this.url.port); + } + + var reqHeaders = headers || {}; + extend(reqHeaders, { + 'Upgrade': 'websocket', + 'Connection': 'Upgrade', + 'Sec-WebSocket-Version': this.config.webSocketVersion.toString(10), + 'Sec-WebSocket-Key': this.base64nonce, + 'Host': reqHeaders.Host || hostHeaderValue + }); + + if (this.protocols.length > 0) { + reqHeaders['Sec-WebSocket-Protocol'] = this.protocols.join(', '); + } + if (this.origin) { + if (this.config.webSocketVersion === 13) { + reqHeaders['Origin'] = this.origin; + } + else if (this.config.webSocketVersion === 8) { + reqHeaders['Sec-WebSocket-Origin'] = this.origin; + } + } + + // TODO: Implement extensions + + var pathAndQuery; + // Ensure it begins with '/'. + if (this.url.pathname) { + pathAndQuery = this.url.path; + } + else if (this.url.path) { + pathAndQuery = '/' + this.url.path; + } + else { + pathAndQuery = '/'; + } + + function handleRequestError(error) { + self._req = null; + self.emit('connectFailed', error); + } + + var requestOptions = { + agent: false + }; + if (extraRequestOptions) { + extend(requestOptions, extraRequestOptions); + } + // These options are always overridden by the library. The user is not + // allowed to specify these directly. + extend(requestOptions, { + hostname: this.url.hostname, + port: this.url.port, + method: 'GET', + path: pathAndQuery, + headers: reqHeaders + }); + if (this.secure) { + for (var key in self.config.tlsOptions) { + if (self.config.tlsOptions.hasOwnProperty(key)) { + requestOptions[key] = self.config.tlsOptions[key]; + } + } + } + + var req = this._req = (this.secure ? https : http).request(requestOptions); + req.on('upgrade', function handleRequestUpgrade(response, socket, head) { + self._req = null; + req.removeListener('error', handleRequestError); + self.socket = socket; + self.response = response; + self.firstDataChunk = head; + self.validateHandshake(); + }); + req.on('error', handleRequestError); + + req.on('response', function(response) { + self._req = null; + if (utils.eventEmitterListenerCount(self, 'httpResponse') > 0) { + self.emit('httpResponse', response, self); + if (response.socket) { + response.socket.end(); + } + } + else { + var headerDumpParts = []; + for (var headerName in response.headers) { + headerDumpParts.push(headerName + ': ' + response.headers[headerName]); + } + self.failHandshake( + 'Server responded with a non-101 status: ' + + response.statusCode + ' ' + response.statusMessage + + '\nResponse Headers Follow:\n' + + headerDumpParts.join('\n') + '\n' + ); + } + }); + req.end(); +}; + +WebSocketClient.prototype.validateHandshake = function() { + var headers = this.response.headers; + + if (this.protocols.length > 0) { + this.protocol = headers['sec-websocket-protocol']; + if (this.protocol) { + if (this.protocols.indexOf(this.protocol) === -1) { + this.failHandshake('Server did not respond with a requested protocol.'); + return; + } + } + else { + this.failHandshake('Expected a Sec-WebSocket-Protocol header.'); + return; + } + } + + if (!(headers['connection'] && headers['connection'].toLocaleLowerCase() === 'upgrade')) { + this.failHandshake('Expected a Connection: Upgrade header from the server'); + return; + } + + if (!(headers['upgrade'] && headers['upgrade'].toLocaleLowerCase() === 'websocket')) { + this.failHandshake('Expected an Upgrade: websocket header from the server'); + return; + } + + var sha1 = crypto.createHash('sha1'); + sha1.update(this.base64nonce + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); + var expectedKey = sha1.digest('base64'); + + if (!headers['sec-websocket-accept']) { + this.failHandshake('Expected Sec-WebSocket-Accept header from server'); + return; + } + + if (headers['sec-websocket-accept'] !== expectedKey) { + this.failHandshake('Sec-WebSocket-Accept header from server didn\'t match expected value of ' + expectedKey); + return; + } + + // TODO: Support extensions + + this.succeedHandshake(); +}; + +WebSocketClient.prototype.failHandshake = function(errorDescription) { + if (this.socket && this.socket.writable) { + this.socket.end(); + } + this.emit('connectFailed', new Error(errorDescription)); +}; + +WebSocketClient.prototype.succeedHandshake = function() { + var connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config); + + connection.webSocketVersion = this.config.webSocketVersion; + connection._addSocketEventListeners(); + + this.emit('connect', connection); + if (this.firstDataChunk.length > 0) { + connection.handleSocketData(this.firstDataChunk); + } + this.firstDataChunk = null; +}; + +WebSocketClient.prototype.abort = function() { + if (this._req) { + this._req.abort(); + } +}; + +module.exports = WebSocketClient; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketConnection.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..2c19aab9c5b940db173ce3388a1d058ba86fb7cb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketConnection.js @@ -0,0 +1,894 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var util = require('util'); +var utils = require('./utils'); +var EventEmitter = require('events').EventEmitter; +var WebSocketFrame = require('./WebSocketFrame'); +var BufferList = require('../vendor/FastBufferList'); +var Validation = require('./Validation').Validation; + +// Connected, fully-open, ready to send and receive frames +const STATE_OPEN = 'open'; +// Received a close frame from the remote peer +const STATE_PEER_REQUESTED_CLOSE = 'peer_requested_close'; +// Sent close frame to remote peer. No further data can be sent. +const STATE_ENDING = 'ending'; +// Connection is fully closed. No further data can be sent or received. +const STATE_CLOSED = 'closed'; + +var setImmediateImpl = ('setImmediate' in global) ? + global.setImmediate.bind(global) : + process.nextTick.bind(process); + +var idCounter = 0; + +function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) { + this._debug = utils.BufferingLogger('websocket:connection', ++idCounter); + this._debug('constructor'); + + if (this._debug.enabled) { + instrumentSocketForDebugging(this, socket); + } + + // Superclass Constructor + EventEmitter.call(this); + + this._pingListenerCount = 0; + this.on('newListener', function(ev) { + if (ev === 'ping'){ + this._pingListenerCount++; + } + }).on('removeListener', function(ev) { + if (ev === 'ping') { + this._pingListenerCount--; + } + }); + + this.config = config; + this.socket = socket; + this.protocol = protocol; + this.extensions = extensions; + this.remoteAddress = socket.remoteAddress; + this.closeReasonCode = -1; + this.closeDescription = null; + this.closeEventEmitted = false; + + // We have to mask outgoing packets if we're acting as a WebSocket client. + this.maskOutgoingPackets = maskOutgoingPackets; + + // We re-use the same buffers for the mask and frame header for all frames + // received on each connection to avoid a small memory allocation for each + // frame. + this.maskBytes = new Buffer(4); + this.frameHeader = new Buffer(10); + + // the BufferList will handle the data streaming in + this.bufferList = new BufferList(); + + // Prepare for receiving first frame + this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + this.fragmentationSize = 0; // data received so far... + this.frameQueue = []; + + // Various bits of connection state + this.connected = true; + this.state = STATE_OPEN; + this.waitingForCloseResponse = false; + // Received TCP FIN, socket's readable stream is finished. + this.receivedEnd = false; + + this.closeTimeout = this.config.closeTimeout; + this.assembleFragments = this.config.assembleFragments; + this.maxReceivedMessageSize = this.config.maxReceivedMessageSize; + + this.outputBufferFull = false; + this.inputPaused = false; + this.receivedDataHandler = this.processReceivedData.bind(this); + this._closeTimerHandler = this.handleCloseTimer.bind(this); + + // Disable nagle algorithm? + this.socket.setNoDelay(this.config.disableNagleAlgorithm); + + // Make sure there is no socket inactivity timeout + this.socket.setTimeout(0); + + if (this.config.keepalive && !this.config.useNativeKeepalive) { + if (typeof(this.config.keepaliveInterval) !== 'number') { + throw new Error('keepaliveInterval must be specified and numeric ' + + 'if keepalive is true.'); + } + this._keepaliveTimerHandler = this.handleKeepaliveTimer.bind(this); + this.setKeepaliveTimer(); + + if (this.config.dropConnectionOnKeepaliveTimeout) { + if (typeof(this.config.keepaliveGracePeriod) !== 'number') { + throw new Error('keepaliveGracePeriod must be specified and ' + + 'numeric if dropConnectionOnKeepaliveTimeout ' + + 'is true.'); + } + this._gracePeriodTimerHandler = this.handleGracePeriodTimer.bind(this); + } + } + else if (this.config.keepalive && this.config.useNativeKeepalive) { + if (!('setKeepAlive' in this.socket)) { + throw new Error('Unable to use native keepalive: unsupported by ' + + 'this version of Node.'); + } + this.socket.setKeepAlive(true, this.config.keepaliveInterval); + } + + // The HTTP Client seems to subscribe to socket error events + // and re-dispatch them in such a way that doesn't make sense + // for users of our client, so we want to make sure nobody + // else is listening for error events on the socket besides us. + this.socket.removeAllListeners('error'); +} + +WebSocketConnection.CLOSE_REASON_NORMAL = 1000; +WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001; +WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002; +WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003; +WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning. +WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire +WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire +WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007; +WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008; +WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009; +WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010; +WebSocketConnection.CLOSE_REASON_INTERNAL_SERVER_ERROR = 1011; +WebSocketConnection.CLOSE_REASON_TLS_HANDSHAKE_FAILED = 1015; // Not to be used on the wire + +WebSocketConnection.CLOSE_DESCRIPTIONS = { + 1000: 'Normal connection closure', + 1001: 'Remote peer is going away', + 1002: 'Protocol error', + 1003: 'Unprocessable input', + 1004: 'Reserved', + 1005: 'Reason not provided', + 1006: 'Abnormal closure, no further detail available', + 1007: 'Invalid data received', + 1008: 'Policy violation', + 1009: 'Message too big', + 1010: 'Extension requested by client is required', + 1011: 'Internal Server Error', + 1015: 'TLS Handshake Failed' +}; + +function validateCloseReason(code) { + if (code < 1000) { + // Status codes in the range 0-999 are not used + return false; + } + if (code >= 1000 && code <= 2999) { + // Codes from 1000 - 2999 are reserved for use by the protocol. Only + // a few codes are defined, all others are currently illegal. + return [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014].indexOf(code) !== -1; + } + if (code >= 3000 && code <= 3999) { + // Reserved for use by libraries, frameworks, and applications. + // Should be registered with IANA. Interpretation of these codes is + // undefined by the WebSocket protocol. + return true; + } + if (code >= 4000 && code <= 4999) { + // Reserved for private use. Interpretation of these codes is + // undefined by the WebSocket protocol. + return true; + } + if (code >= 5000) { + return false; + } +} + +util.inherits(WebSocketConnection, EventEmitter); + +WebSocketConnection.prototype._addSocketEventListeners = function() { + this.socket.on('error', this.handleSocketError.bind(this)); + this.socket.on('end', this.handleSocketEnd.bind(this)); + this.socket.on('close', this.handleSocketClose.bind(this)); + this.socket.on('drain', this.handleSocketDrain.bind(this)); + this.socket.on('pause', this.handleSocketPause.bind(this)); + this.socket.on('resume', this.handleSocketResume.bind(this)); + this.socket.on('data', this.handleSocketData.bind(this)); +}; + +// set or reset the keepalive timer when data is received. +WebSocketConnection.prototype.setKeepaliveTimer = function() { + this._debug('setKeepaliveTimer'); + if (!this.config.keepalive || this.config.useNativeKeepalive) { return; } + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + this._keepaliveTimeoutID = setTimeout(this._keepaliveTimerHandler, this.config.keepaliveInterval); +}; + +WebSocketConnection.prototype.clearKeepaliveTimer = function() { + if (this._keepaliveTimeoutID) { + clearTimeout(this._keepaliveTimeoutID); + } +}; + +// No data has been received within config.keepaliveTimeout ms. +WebSocketConnection.prototype.handleKeepaliveTimer = function() { + this._debug('handleKeepaliveTimer'); + this._keepaliveTimeoutID = null; + this.ping(); + + // If we are configured to drop connections if the client doesn't respond + // then set the grace period timer. + if (this.config.dropConnectionOnKeepaliveTimeout) { + this.setGracePeriodTimer(); + } + else { + // Otherwise reset the keepalive timer to send the next ping. + this.setKeepaliveTimer(); + } +}; + +WebSocketConnection.prototype.setGracePeriodTimer = function() { + this._debug('setGracePeriodTimer'); + this.clearGracePeriodTimer(); + this._gracePeriodTimeoutID = setTimeout(this._gracePeriodTimerHandler, this.config.keepaliveGracePeriod); +}; + +WebSocketConnection.prototype.clearGracePeriodTimer = function() { + if (this._gracePeriodTimeoutID) { + clearTimeout(this._gracePeriodTimeoutID); + } +}; + +WebSocketConnection.prototype.handleGracePeriodTimer = function() { + this._debug('handleGracePeriodTimer'); + // If this is called, the client has not responded and is assumed dead. + this._gracePeriodTimeoutID = null; + this.drop(WebSocketConnection.CLOSE_REASON_ABNORMAL, 'Peer not responding.', true); +}; + +WebSocketConnection.prototype.handleSocketData = function(data) { + this._debug('handleSocketData'); + // Reset the keepalive timer when receiving data of any kind. + this.setKeepaliveTimer(); + + // Add received data to our bufferList, which efficiently holds received + // data chunks in a linked list of Buffer objects. + this.bufferList.write(data); + + this.processReceivedData(); +}; + +WebSocketConnection.prototype.processReceivedData = function() { + this._debug('processReceivedData'); + // If we're not connected, we should ignore any data remaining on the buffer. + if (!this.connected) { return; } + + // Receiving/parsing is expected to be halted when paused. + if (this.inputPaused) { return; } + + var frame = this.currentFrame; + + // WebSocketFrame.prototype.addData returns true if all data necessary to + // parse the frame was available. It returns false if we are waiting for + // more data to come in on the wire. + if (!frame.addData(this.bufferList)) { this._debug('-- insufficient data for frame'); return; } + + var self = this; + + // Handle possible parsing errors + if (frame.protocolError) { + // Something bad happened.. get rid of this client. + this._debug('-- protocol error'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, frame.dropReason); + }); + return; + } + else if (frame.frameTooLarge) { + this._debug('-- frame too large'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, frame.dropReason); + }); + return; + } + + // For now since we don't support extensions, all RSV bits are illegal + if (frame.rsv1 || frame.rsv2 || frame.rsv3) { + this._debug('-- illegal rsv flag'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unsupported usage of rsv bits without negotiated extension.'); + }); + return; + } + + if (!this.assembleFragments) { + this._debug('-- emitting frame'); + process.nextTick(function() { self.emit('frame', frame); }); + } + + process.nextTick(function() { self.processFrame(frame); }); + + this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + + // If there's data remaining, schedule additional processing, but yield + // for now so that other connections have a chance to have their data + // processed. We use setImmediate here instead of process.nextTick to + // explicitly indicate that we wish for other I/O to be handled first. + if (this.bufferList.length > 0) { + setImmediateImpl(this.receivedDataHandler); + } +}; + +WebSocketConnection.prototype.handleSocketError = function(error) { + this._debug('handleSocketError: %j', error); + if (this.state === STATE_CLOSED) { + // See https://github.com/theturtle32/WebSocket-Node/issues/288 + this._debug(' --- Socket \'error\' after \'close\''); + return; + } + this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL; + this.closeDescription = 'Socket Error: ' + error.syscall + ' ' + error.code; + this.connected = false; + this.state = STATE_CLOSED; + this.fragmentationSize = 0; + if (utils.eventEmitterListenerCount(this, 'error') > 0) { + this.emit('error', error); + } + this.socket.destroy(error); + this._debug.printOutput(); +}; + +WebSocketConnection.prototype.handleSocketEnd = function() { + this._debug('handleSocketEnd: received socket end. state = %s', this.state); + this.receivedEnd = true; + if (this.state === STATE_CLOSED) { + // When using the TLS module, sometimes the socket will emit 'end' + // after it emits 'close'. I don't think that's correct behavior, + // but we should deal with it gracefully by ignoring it. + this._debug(' --- Socket \'end\' after \'close\''); + return; + } + if (this.state !== STATE_PEER_REQUESTED_CLOSE && + this.state !== STATE_ENDING) { + this._debug(' --- UNEXPECTED socket end.'); + this.socket.end(); + } +}; + +WebSocketConnection.prototype.handleSocketClose = function(hadError) { + this._debug('handleSocketClose: received socket close'); + this.socketHadError = hadError; + this.connected = false; + this.state = STATE_CLOSED; + // If closeReasonCode is still set to -1 at this point then we must + // not have received a close frame!! + if (this.closeReasonCode === -1) { + this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL; + this.closeDescription = 'Connection dropped by remote peer.'; + } + this.clearCloseTimer(); + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + if (!this.closeEventEmitted) { + this.closeEventEmitted = true; + this._debug('-- Emitting WebSocketConnection close event'); + this.emit('close', this.closeReasonCode, this.closeDescription); + } +}; + +WebSocketConnection.prototype.handleSocketDrain = function() { + this._debug('handleSocketDrain: socket drain event'); + this.outputBufferFull = false; + this.emit('drain'); +}; + +WebSocketConnection.prototype.handleSocketPause = function() { + this._debug('handleSocketPause: socket pause event'); + this.inputPaused = true; + this.emit('pause'); +}; + +WebSocketConnection.prototype.handleSocketResume = function() { + this._debug('handleSocketResume: socket resume event'); + this.inputPaused = false; + this.emit('resume'); + this.processReceivedData(); +}; + +WebSocketConnection.prototype.pause = function() { + this._debug('pause: pause requested'); + this.socket.pause(); +}; + +WebSocketConnection.prototype.resume = function() { + this._debug('resume: resume requested'); + this.socket.resume(); +}; + +WebSocketConnection.prototype.close = function(reasonCode, description) { + if (this.connected) { + this._debug('close: Initating clean WebSocket close sequence.'); + if ('number' !== typeof reasonCode) { + reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + if (!validateCloseReason(reasonCode)) { + throw new Error('Close code ' + reasonCode + ' is not valid.'); + } + if ('string' !== typeof description) { + description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode]; + } + this.closeReasonCode = reasonCode; + this.closeDescription = description; + this.setCloseTimer(); + this.sendCloseFrame(this.closeReasonCode, this.closeDescription); + this.state = STATE_ENDING; + this.connected = false; + } +}; + +WebSocketConnection.prototype.drop = function(reasonCode, description, skipCloseFrame) { + this._debug('drop'); + if (typeof(reasonCode) !== 'number') { + reasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + + if (typeof(description) !== 'string') { + // If no description is provided, try to look one up based on the + // specified reasonCode. + description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode]; + } + + this._debug('Forcefully dropping connection. skipCloseFrame: %s, code: %d, description: %s', + skipCloseFrame, reasonCode, description + ); + + this.closeReasonCode = reasonCode; + this.closeDescription = description; + this.frameQueue = []; + this.fragmentationSize = 0; + if (!skipCloseFrame) { + this.sendCloseFrame(reasonCode, description); + } + this.connected = false; + this.state = STATE_CLOSED; + this.clearCloseTimer(); + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + + if (!this.closeEventEmitted) { + this.closeEventEmitted = true; + this._debug('Emitting WebSocketConnection close event'); + this.emit('close', this.closeReasonCode, this.closeDescription); + } + + this._debug('Drop: destroying socket'); + this.socket.destroy(); +}; + +WebSocketConnection.prototype.setCloseTimer = function() { + this._debug('setCloseTimer'); + this.clearCloseTimer(); + this._debug('Setting close timer'); + this.waitingForCloseResponse = true; + this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout); +}; + +WebSocketConnection.prototype.clearCloseTimer = function() { + this._debug('clearCloseTimer'); + if (this.closeTimer) { + this._debug('Clearing close timer'); + clearTimeout(this.closeTimer); + this.waitingForCloseResponse = false; + this.closeTimer = null; + } +}; + +WebSocketConnection.prototype.handleCloseTimer = function() { + this._debug('handleCloseTimer'); + this.closeTimer = null; + if (this.waitingForCloseResponse) { + this._debug('Close response not received from client. Forcing socket end.'); + this.waitingForCloseResponse = false; + this.state = STATE_CLOSED; + this.socket.end(); + } +}; + +WebSocketConnection.prototype.processFrame = function(frame) { + this._debug('processFrame'); + this._debug(' -- frame: %s', frame); + + // Any non-control opcode besides 0x00 (continuation) received in the + // middle of a fragmented message is illegal. + if (this.frameQueue.length !== 0 && (frame.opcode > 0x00 && frame.opcode < 0x08)) { + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Illegal frame opcode 0x' + frame.opcode.toString(16) + ' ' + + 'received in middle of fragmented message.'); + return; + } + + switch(frame.opcode) { + case 0x02: // WebSocketFrame.BINARY_FRAME + this._debug('-- Binary Frame'); + if (this.assembleFragments) { + if (frame.fin) { + // Complete single-frame message received + this._debug('---- Emitting \'message\' event'); + this.emit('message', { + type: 'binary', + binaryData: frame.binaryPayload + }); + } + else { + // beginning of a fragmented message + this.frameQueue.push(frame); + this.fragmentationSize = frame.length; + } + } + break; + case 0x01: // WebSocketFrame.TEXT_FRAME + this._debug('-- Text Frame'); + if (this.assembleFragments) { + if (frame.fin) { + if (!Validation.isValidUTF8(frame.binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + // Complete single-frame message received + this._debug('---- Emitting \'message\' event'); + this.emit('message', { + type: 'utf8', + utf8Data: frame.binaryPayload.toString('utf8') + }); + } + else { + // beginning of a fragmented message + this.frameQueue.push(frame); + this.fragmentationSize = frame.length; + } + } + break; + case 0x00: // WebSocketFrame.CONTINUATION + this._debug('-- Continuation Frame'); + if (this.assembleFragments) { + if (this.frameQueue.length === 0) { + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unexpected Continuation Frame'); + return; + } + + this.fragmentationSize += frame.length; + + if (this.fragmentationSize > this.maxReceivedMessageSize) { + this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, + 'Maximum message size exceeded.'); + return; + } + + this.frameQueue.push(frame); + + if (frame.fin) { + // end of fragmented message, so we process the whole + // message now. We also have to decode the utf-8 data + // for text frames after combining all the fragments. + var bytesCopied = 0; + var binaryPayload = new Buffer(this.fragmentationSize); + var opcode = this.frameQueue[0].opcode; + this.frameQueue.forEach(function (currentFrame) { + currentFrame.binaryPayload.copy(binaryPayload, bytesCopied); + bytesCopied += currentFrame.binaryPayload.length; + }); + this.frameQueue = []; + this.fragmentationSize = 0; + + switch (opcode) { + case 0x02: // WebSocketOpcode.BINARY_FRAME + this.emit('message', { + type: 'binary', + binaryData: binaryPayload + }); + break; + case 0x01: // WebSocketOpcode.TEXT_FRAME + if (!Validation.isValidUTF8(binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + this.emit('message', { + type: 'utf8', + utf8Data: binaryPayload.toString('utf8') + }); + break; + default: + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unexpected first opcode in fragmentation sequence: 0x' + opcode.toString(16)); + return; + } + } + } + break; + case 0x09: // WebSocketFrame.PING + this._debug('-- Ping Frame'); + + if (this._pingListenerCount > 0) { + // logic to emit the ping frame: this is only done when a listener is known to exist + // Expose a function allowing the user to override the default ping() behavior + var cancelled = false; + var cancel = function() { + cancelled = true; + }; + this.emit('ping', cancel, frame.binaryPayload); + + // Only send a pong if the client did not indicate that he would like to cancel + if (!cancelled) { + this.pong(frame.binaryPayload); + } + } + else { + this.pong(frame.binaryPayload); + } + + break; + case 0x0A: // WebSocketFrame.PONG + this._debug('-- Pong Frame'); + this.emit('pong', frame.binaryPayload); + break; + case 0x08: // WebSocketFrame.CONNECTION_CLOSE + this._debug('-- Close Frame'); + if (this.waitingForCloseResponse) { + // Got response to our request to close the connection. + // Close is complete, so we just hang up. + this._debug('---- Got close response from peer. Completing closing handshake.'); + this.clearCloseTimer(); + this.waitingForCloseResponse = false; + this.state = STATE_CLOSED; + this.socket.end(); + return; + } + + this._debug('---- Closing handshake initiated by peer.'); + // Got request from other party to close connection. + // Send back acknowledgement and then hang up. + this.state = STATE_PEER_REQUESTED_CLOSE; + var respondCloseReasonCode; + + // Make sure the close reason provided is legal according to + // the protocol spec. Providing no close status is legal. + // WebSocketFrame sets closeStatus to -1 by default, so if it + // is still -1, then no status was provided. + if (frame.invalidCloseFrameLength) { + this.closeReasonCode = 1005; // 1005 = No reason provided. + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + else if (frame.closeStatus === -1 || validateCloseReason(frame.closeStatus)) { + this.closeReasonCode = frame.closeStatus; + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + else { + this.closeReasonCode = frame.closeStatus; + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + + // If there is a textual description in the close frame, extract it. + if (frame.binaryPayload.length > 1) { + if (!Validation.isValidUTF8(frame.binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + this.closeDescription = frame.binaryPayload.toString('utf8'); + } + else { + this.closeDescription = WebSocketConnection.CLOSE_DESCRIPTIONS[this.closeReasonCode]; + } + this._debug( + '------ Remote peer %s - code: %d - %s - close frame payload length: %d', + this.remoteAddress, this.closeReasonCode, + this.closeDescription, frame.length + ); + this._debug('------ responding to remote peer\'s close request.'); + this.sendCloseFrame(respondCloseReasonCode, null); + this.connected = false; + break; + default: + this._debug('-- Unrecognized Opcode %d', frame.opcode); + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unrecognized Opcode: 0x' + frame.opcode.toString(16)); + break; + } +}; + +WebSocketConnection.prototype.send = function(data, cb) { + this._debug('send'); + if (Buffer.isBuffer(data)) { + this.sendBytes(data, cb); + } + else if (typeof(data['toString']) === 'function') { + this.sendUTF(data, cb); + } + else { + throw new Error('Data provided must either be a Node Buffer or implement toString()'); + } +}; + +WebSocketConnection.prototype.sendUTF = function(data, cb) { + data = new Buffer(data.toString(), 'utf8'); + this._debug('sendUTF: %d bytes', data.length); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME + frame.binaryPayload = data; + this.fragmentAndSend(frame, cb); +}; + +WebSocketConnection.prototype.sendBytes = function(data, cb) { + this._debug('sendBytes'); + if (!Buffer.isBuffer(data)) { + throw new Error('You must pass a Node Buffer object to WebSocketConnection.prototype.sendBytes()'); + } + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME + frame.binaryPayload = data; + this.fragmentAndSend(frame, cb); +}; + +WebSocketConnection.prototype.ping = function(data) { + this._debug('ping'); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x09; // WebSocketOpcode.PING + frame.fin = true; + if (data) { + if (!Buffer.isBuffer(data)) { + data = new Buffer(data.toString(), 'utf8'); + } + if (data.length > 125) { + this._debug('WebSocket: Data for ping is longer than 125 bytes. Truncating.'); + data = data.slice(0,124); + } + frame.binaryPayload = data; + } + this.sendFrame(frame); +}; + +// Pong frames have to echo back the contents of the data portion of the +// ping frame exactly, byte for byte. +WebSocketConnection.prototype.pong = function(binaryPayload) { + this._debug('pong'); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x0A; // WebSocketOpcode.PONG + if (Buffer.isBuffer(binaryPayload) && binaryPayload.length > 125) { + this._debug('WebSocket: Data for pong is longer than 125 bytes. Truncating.'); + binaryPayload = binaryPayload.slice(0,124); + } + frame.binaryPayload = binaryPayload; + frame.fin = true; + this.sendFrame(frame); +}; + +WebSocketConnection.prototype.fragmentAndSend = function(frame, cb) { + this._debug('fragmentAndSend'); + if (frame.opcode > 0x07) { + throw new Error('You cannot fragment control frames.'); + } + + var threshold = this.config.fragmentationThreshold; + var length = frame.binaryPayload.length; + + // Send immediately if fragmentation is disabled or the message is not + // larger than the fragmentation threshold. + if (!this.config.fragmentOutgoingMessages || (frame.binaryPayload && length <= threshold)) { + frame.fin = true; + this.sendFrame(frame, cb); + return; + } + + var numFragments = Math.ceil(length / threshold); + var sentFragments = 0; + var sentCallback = function fragmentSentCallback(err) { + if (err) { + if (typeof cb === 'function') { + // pass only the first error + cb(err); + cb = null; + } + return; + } + ++sentFragments; + if ((sentFragments === numFragments) && (typeof cb === 'function')) { + cb(); + } + }; + for (var i=1; i <= numFragments; i++) { + var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + + // continuation opcode except for first frame. + currentFrame.opcode = (i === 1) ? frame.opcode : 0x00; + + // fin set on last frame only + currentFrame.fin = (i === numFragments); + + // length is likely to be shorter on the last fragment + var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold; + var sliceStart = threshold * (i-1); + + // Slice the right portion of the original payload + currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength); + + this.sendFrame(currentFrame, sentCallback); + } +}; + +WebSocketConnection.prototype.sendCloseFrame = function(reasonCode, description, cb) { + if (typeof(reasonCode) !== 'number') { + reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + + this._debug('sendCloseFrame state: %s, reasonCode: %d, description: %s', this.state, reasonCode, description); + + if (this.state !== STATE_OPEN && this.state !== STATE_PEER_REQUESTED_CLOSE) { return; } + + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.fin = true; + frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE + frame.closeStatus = reasonCode; + if (typeof(description) === 'string') { + frame.binaryPayload = new Buffer(description, 'utf8'); + } + + this.sendFrame(frame, cb); + this.socket.end(); +}; + +WebSocketConnection.prototype.sendFrame = function(frame, cb) { + this._debug('sendFrame'); + frame.mask = this.maskOutgoingPackets; + var flushed = this.socket.write(frame.toBuffer(), cb); + this.outputBufferFull = !flushed; + return flushed; +}; + +module.exports = WebSocketConnection; + + + +function instrumentSocketForDebugging(connection, socket) { + /* jshint loopfunc: true */ + if (!connection._debug.enabled) { return; } + + var originalSocketEmit = socket.emit; + socket.emit = function(event) { + connection._debug('||| Socket Event \'%s\'', event); + originalSocketEmit.apply(this, arguments); + }; + + for (var key in socket) { + if ('function' !== typeof(socket[key])) { continue; } + if (['emit'].indexOf(key) !== -1) { continue; } + (function(key) { + var original = socket[key]; + if (key === 'on') { + socket[key] = function proxyMethod__EventEmitter__On() { + connection._debug('||| Socket method called: %s (%s)', key, arguments[0]); + return original.apply(this, arguments); + }; + return; + } + socket[key] = function proxyMethod() { + connection._debug('||| Socket method called: %s', key); + return original.apply(this, arguments); + }; + })(key); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketFrame.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketFrame.js new file mode 100644 index 0000000000000000000000000000000000000000..859e8797d3ae7cd4998fe121df12d399099dcfc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketFrame.js @@ -0,0 +1,279 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var bufferUtil = require('./BufferUtil').BufferUtil; + +const DECODE_HEADER = 1; +const WAITING_FOR_16_BIT_LENGTH = 2; +const WAITING_FOR_64_BIT_LENGTH = 3; +const WAITING_FOR_MASK_KEY = 4; +const WAITING_FOR_PAYLOAD = 5; +const COMPLETE = 6; + +// WebSocketConnection will pass shared buffer objects for maskBytes and +// frameHeader into the constructor to avoid tons of small memory allocations +// for each frame we have to parse. This is only used for parsing frames +// we receive off the wire. +function WebSocketFrame(maskBytes, frameHeader, config) { + this.maskBytes = maskBytes; + this.frameHeader = frameHeader; + this.config = config; + this.maxReceivedFrameSize = config.maxReceivedFrameSize; + this.protocolError = false; + this.frameTooLarge = false; + this.invalidCloseFrameLength = false; + this.parseState = DECODE_HEADER; + this.closeStatus = -1; +} + +WebSocketFrame.prototype.addData = function(bufferList) { + if (this.parseState === DECODE_HEADER) { + if (bufferList.length >= 2) { + bufferList.joinInto(this.frameHeader, 0, 0, 2); + bufferList.advance(2); + var firstByte = this.frameHeader[0]; + var secondByte = this.frameHeader[1]; + + this.fin = Boolean(firstByte & 0x80); + this.rsv1 = Boolean(firstByte & 0x40); + this.rsv2 = Boolean(firstByte & 0x20); + this.rsv3 = Boolean(firstByte & 0x10); + this.mask = Boolean(secondByte & 0x80); + + this.opcode = firstByte & 0x0F; + this.length = secondByte & 0x7F; + + // Control frame sanity check + if (this.opcode >= 0x08) { + if (this.length > 125) { + this.protocolError = true; + this.dropReason = 'Illegal control frame longer than 125 bytes.'; + return true; + } + if (!this.fin) { + this.protocolError = true; + this.dropReason = 'Control frames must not be fragmented.'; + return true; + } + } + + if (this.length === 126) { + this.parseState = WAITING_FOR_16_BIT_LENGTH; + } + else if (this.length === 127) { + this.parseState = WAITING_FOR_64_BIT_LENGTH; + } + else { + this.parseState = WAITING_FOR_MASK_KEY; + } + } + } + if (this.parseState === WAITING_FOR_16_BIT_LENGTH) { + if (bufferList.length >= 2) { + bufferList.joinInto(this.frameHeader, 2, 0, 2); + bufferList.advance(2); + this.length = this.frameHeader.readUInt16BE(2, true); + this.parseState = WAITING_FOR_MASK_KEY; + } + } + else if (this.parseState === WAITING_FOR_64_BIT_LENGTH) { + if (bufferList.length >= 8) { + bufferList.joinInto(this.frameHeader, 2, 0, 8); + bufferList.advance(8); + var lengthPair = [ + this.frameHeader.readUInt32BE(2, true), + this.frameHeader.readUInt32BE(2+4, true) + ]; + + if (lengthPair[0] !== 0) { + this.protocolError = true; + this.dropReason = 'Unsupported 64-bit length frame received'; + return true; + } + this.length = lengthPair[1]; + this.parseState = WAITING_FOR_MASK_KEY; + } + } + + if (this.parseState === WAITING_FOR_MASK_KEY) { + if (this.mask) { + if (bufferList.length >= 4) { + bufferList.joinInto(this.maskBytes, 0, 0, 4); + bufferList.advance(4); + this.parseState = WAITING_FOR_PAYLOAD; + } + } + else { + this.parseState = WAITING_FOR_PAYLOAD; + } + } + + if (this.parseState === WAITING_FOR_PAYLOAD) { + if (this.length > this.maxReceivedFrameSize) { + this.frameTooLarge = true; + this.dropReason = 'Frame size of ' + this.length.toString(10) + + ' bytes exceeds maximum accepted frame size'; + return true; + } + + if (this.length === 0) { + this.binaryPayload = new Buffer(0); + this.parseState = COMPLETE; + return true; + } + if (bufferList.length >= this.length) { + this.binaryPayload = bufferList.take(this.length); + bufferList.advance(this.length); + if (this.mask) { + bufferUtil.unmask(this.binaryPayload, this.maskBytes); + // xor(this.binaryPayload, this.maskBytes, 0); + } + + if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE + if (this.length === 1) { + // Invalid length for a close frame. Must be zero or at least two. + this.binaryPayload = new Buffer(0); + this.invalidCloseFrameLength = true; + } + if (this.length >= 2) { + this.closeStatus = this.binaryPayload.readUInt16BE(0, true); + this.binaryPayload = this.binaryPayload.slice(2); + } + } + + this.parseState = COMPLETE; + return true; + } + } + return false; +}; + +WebSocketFrame.prototype.throwAwayPayload = function(bufferList) { + if (bufferList.length >= this.length) { + bufferList.advance(this.length); + this.parseState = COMPLETE; + return true; + } + return false; +}; + +WebSocketFrame.prototype.toBuffer = function(nullMask) { + var maskKey; + var headerLength = 2; + var data; + var outputPos; + var firstByte = 0x00; + var secondByte = 0x00; + + if (this.fin) { + firstByte |= 0x80; + } + if (this.rsv1) { + firstByte |= 0x40; + } + if (this.rsv2) { + firstByte |= 0x20; + } + if (this.rsv3) { + firstByte |= 0x10; + } + if (this.mask) { + secondByte |= 0x80; + } + + firstByte |= (this.opcode & 0x0F); + + // the close frame is a special case because the close reason is + // prepended to the payload data. + if (this.opcode === 0x08) { + this.length = 2; + if (this.binaryPayload) { + this.length += this.binaryPayload.length; + } + data = new Buffer(this.length); + data.writeUInt16BE(this.closeStatus, 0, true); + if (this.length > 2) { + this.binaryPayload.copy(data, 2); + } + } + else if (this.binaryPayload) { + data = this.binaryPayload; + this.length = data.length; + } + else { + this.length = 0; + } + + if (this.length <= 125) { + // encode the length directly into the two-byte frame header + secondByte |= (this.length & 0x7F); + } + else if (this.length > 125 && this.length <= 0xFFFF) { + // Use 16-bit length + secondByte |= 126; + headerLength += 2; + } + else if (this.length > 0xFFFF) { + // Use 64-bit length + secondByte |= 127; + headerLength += 8; + } + + var output = new Buffer(this.length + headerLength + (this.mask ? 4 : 0)); + + // write the frame header + output[0] = firstByte; + output[1] = secondByte; + + outputPos = 2; + + if (this.length > 125 && this.length <= 0xFFFF) { + // write 16-bit length + output.writeUInt16BE(this.length, outputPos, true); + outputPos += 2; + } + else if (this.length > 0xFFFF) { + // write 64-bit length + output.writeUInt32BE(0x00000000, outputPos, true); + output.writeUInt32BE(this.length, outputPos + 4, true); + outputPos += 8; + } + + if (this.mask) { + maskKey = nullMask ? 0 : (Math.random()*0xFFFFFFFF) | 0; + this.maskBytes.writeUInt32BE(maskKey, 0, true); + + // write the mask key + this.maskBytes.copy(output, outputPos); + outputPos += 4; + + if (data) { + bufferUtil.mask(data, this.maskBytes, output, outputPos, this.length); + } + } + else if (data) { + data.copy(output, outputPos); + } + + return output; +}; + +WebSocketFrame.prototype.toString = function() { + return 'Opcode: ' + this.opcode + ', fin: ' + this.fin + ', length: ' + this.length + ', hasPayload: ' + Boolean(this.binaryPayload) + ', masked: ' + this.mask; +}; + + +module.exports = WebSocketFrame; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRequest.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..f4d96555f9597661244c17265c4e1b144b05cf94 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRequest.js @@ -0,0 +1,524 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var crypto = require('crypto'); +var util = require('util'); +var url = require('url'); +var EventEmitter = require('events').EventEmitter; +var WebSocketConnection = require('./WebSocketConnection'); + +var headerValueSplitRegExp = /,\s*/; +var headerParamSplitRegExp = /;\s*/; +var headerSanitizeRegExp = /[\r\n]/g; +var xForwardedForSeparatorRegExp = /,\s*/; +var separators = [ + '(', ')', '<', '>', '@', + ',', ';', ':', '\\', '\"', + '/', '[', ']', '?', '=', + '{', '}', ' ', String.fromCharCode(9) +]; +var controlChars = [String.fromCharCode(127) /* DEL */]; +for (var i=0; i < 31; i ++) { + /* US-ASCII Control Characters */ + controlChars.push(String.fromCharCode(i)); +} + +var cookieNameValidateRegEx = /([\x00-\x20\x22\x28\x29\x2c\x2f\x3a-\x3f\x40\x5b-\x5e\x7b\x7d\x7f])/; +var cookieValueValidateRegEx = /[^\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]/; +var cookieValueDQuoteValidateRegEx = /^"[^"]*"$/; +var controlCharsAndSemicolonRegEx = /[\x00-\x20\x3b]/g; + +var cookieSeparatorRegEx = /[;,] */; + +var httpStatusDescriptions = { + 100: 'Continue', + 101: 'Switching Protocols', + 200: 'OK', + 201: 'Created', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Found', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary Redirect', + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 406: 'Not Acceptable', + 407: 'Proxy Authorization Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Long', + 414: 'Request-URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 426: 'Upgrade Required', + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Timeout', + 505: 'HTTP Version Not Supported' +}; + +function WebSocketRequest(socket, httpRequest, serverConfig) { + // Superclass Constructor + EventEmitter.call(this); + + this.socket = socket; + this.httpRequest = httpRequest; + this.resource = httpRequest.url; + this.remoteAddress = socket.remoteAddress; + this.remoteAddresses = [this.remoteAddress]; + this.serverConfig = serverConfig; + + // Watch for the underlying TCP socket closing before we call accept + this._socketIsClosing = false; + this._socketCloseHandler = this._handleSocketCloseBeforeAccept.bind(this); + this.socket.on('end', this._socketCloseHandler); + this.socket.on('close', this._socketCloseHandler); + + this._resolved = false; +} + +util.inherits(WebSocketRequest, EventEmitter); + +WebSocketRequest.prototype.readHandshake = function() { + var self = this; + var request = this.httpRequest; + + // Decode URL + this.resourceURL = url.parse(this.resource, true); + + this.host = request.headers['host']; + if (!this.host) { + throw new Error('Client must provide a Host header.'); + } + + this.key = request.headers['sec-websocket-key']; + if (!this.key) { + throw new Error('Client must provide a value for Sec-WebSocket-Key.'); + } + + this.webSocketVersion = parseInt(request.headers['sec-websocket-version'], 10); + + if (!this.webSocketVersion || isNaN(this.webSocketVersion)) { + throw new Error('Client must provide a value for Sec-WebSocket-Version.'); + } + + switch (this.webSocketVersion) { + case 8: + case 13: + break; + default: + var e = new Error('Unsupported websocket client version: ' + this.webSocketVersion + + 'Only versions 8 and 13 are supported.'); + e.httpCode = 426; + e.headers = { + 'Sec-WebSocket-Version': '13' + }; + throw e; + } + + if (this.webSocketVersion === 13) { + this.origin = request.headers['origin']; + } + else if (this.webSocketVersion === 8) { + this.origin = request.headers['sec-websocket-origin']; + } + + // Protocol is optional. + var protocolString = request.headers['sec-websocket-protocol']; + this.protocolFullCaseMap = {}; + this.requestedProtocols = []; + if (protocolString) { + var requestedProtocolsFullCase = protocolString.split(headerValueSplitRegExp); + requestedProtocolsFullCase.forEach(function(protocol) { + var lcProtocol = protocol.toLocaleLowerCase(); + self.requestedProtocols.push(lcProtocol); + self.protocolFullCaseMap[lcProtocol] = protocol; + }); + } + + if (!this.serverConfig.ignoreXForwardedFor && + request.headers['x-forwarded-for']) { + var immediatePeerIP = this.remoteAddress; + this.remoteAddresses = request.headers['x-forwarded-for'] + .split(xForwardedForSeparatorRegExp); + this.remoteAddresses.push(immediatePeerIP); + this.remoteAddress = this.remoteAddresses[0]; + } + + // Extensions are optional. + var extensionsString = request.headers['sec-websocket-extensions']; + this.requestedExtensions = this.parseExtensions(extensionsString); + + // Cookies are optional + var cookieString = request.headers['cookie']; + this.cookies = this.parseCookies(cookieString); +}; + +WebSocketRequest.prototype.parseExtensions = function(extensionsString) { + if (!extensionsString || extensionsString.length === 0) { + return []; + } + var extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp); + extensions.forEach(function(extension, index, array) { + var params = extension.split(headerParamSplitRegExp); + var extensionName = params[0]; + var extensionParams = params.slice(1); + extensionParams.forEach(function(rawParam, index, array) { + var arr = rawParam.split('='); + var obj = { + name: arr[0], + value: arr[1] + }; + array.splice(index, 1, obj); + }); + var obj = { + name: extensionName, + params: extensionParams + }; + array.splice(index, 1, obj); + }); + return extensions; +}; + +// This function adapted from node-cookie +// https://github.com/shtylman/node-cookie +WebSocketRequest.prototype.parseCookies = function(str) { + // Sanity Check + if (!str || typeof(str) !== 'string') { + return []; + } + + var cookies = []; + var pairs = str.split(cookieSeparatorRegEx); + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('='); + if (eq_idx === -1) { + cookies.push({ + name: pair, + value: null + }); + return; + } + + var key = pair.substr(0, eq_idx).trim(); + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' === val[0]) { + val = val.slice(1, -1); + } + + cookies.push({ + name: key, + value: decodeURIComponent(val) + }); + }); + + return cookies; +}; + +WebSocketRequest.prototype.accept = function(acceptedProtocol, allowedOrigin, cookies) { + this._verifyResolution(); + + // TODO: Handle extensions + + var protocolFullCase; + + if (acceptedProtocol) { + protocolFullCase = this.protocolFullCaseMap[acceptedProtocol.toLocaleLowerCase()]; + if (typeof(protocolFullCase) === 'undefined') { + protocolFullCase = acceptedProtocol; + } + } + else { + protocolFullCase = acceptedProtocol; + } + this.protocolFullCaseMap = null; + + // Create key validation hash + var sha1 = crypto.createHash('sha1'); + sha1.update(this.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); + var acceptKey = sha1.digest('base64'); + + var response = 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: ' + acceptKey + '\r\n'; + + if (protocolFullCase) { + // validate protocol + for (var i=0; i < protocolFullCase.length; i++) { + var charCode = protocolFullCase.charCodeAt(i); + var character = protocolFullCase.charAt(i); + if (charCode < 0x21 || charCode > 0x7E || separators.indexOf(character) !== -1) { + this.reject(500); + throw new Error('Illegal character "' + String.fromCharCode(character) + '" in subprotocol.'); + } + } + if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) { + this.reject(500); + throw new Error('Specified protocol was not requested by the client.'); + } + + protocolFullCase = protocolFullCase.replace(headerSanitizeRegExp, ''); + response += 'Sec-WebSocket-Protocol: ' + protocolFullCase + '\r\n'; + } + this.requestedProtocols = null; + + if (allowedOrigin) { + allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, ''); + if (this.webSocketVersion === 13) { + response += 'Origin: ' + allowedOrigin + '\r\n'; + } + else if (this.webSocketVersion === 8) { + response += 'Sec-WebSocket-Origin: ' + allowedOrigin + '\r\n'; + } + } + + if (cookies) { + if (!Array.isArray(cookies)) { + this.reject(500); + throw new Error('Value supplied for "cookies" argument must be an array.'); + } + var seenCookies = {}; + cookies.forEach(function(cookie) { + if (!cookie.name || !cookie.value) { + this.reject(500); + throw new Error('Each cookie to set must at least provide a "name" and "value"'); + } + + // Make sure there are no \r\n sequences inserted + cookie.name = cookie.name.replace(controlCharsAndSemicolonRegEx, ''); + cookie.value = cookie.value.replace(controlCharsAndSemicolonRegEx, ''); + + if (seenCookies[cookie.name]) { + this.reject(500); + throw new Error('You may not specify the same cookie name twice.'); + } + seenCookies[cookie.name] = true; + + // token (RFC 2616, Section 2.2) + var invalidChar = cookie.name.match(cookieNameValidateRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie name'); + } + + // RFC 6265, Section 4.1.1 + // *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) | %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + if (cookie.value.match(cookieValueDQuoteValidateRegEx)) { + invalidChar = cookie.value.slice(1, -1).match(cookieValueValidateRegEx); + } else { + invalidChar = cookie.value.match(cookieValueValidateRegEx); + } + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie value'); + } + + var cookieParts = [cookie.name + '=' + cookie.value]; + + // RFC 6265, Section 4.1.1 + // 'Path=' path-value | <any CHAR except CTLs or ';'> + if(cookie.path){ + invalidChar = cookie.path.match(controlCharsAndSemicolonRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie path'); + } + cookieParts.push('Path=' + cookie.path); + } + + // RFC 6265, Section 4.1.2.3 + // 'Domain=' subdomain + if (cookie.domain) { + if (typeof(cookie.domain) !== 'string') { + this.reject(500); + throw new Error('Domain must be specified and must be a string.'); + } + invalidChar = cookie.domain.match(controlCharsAndSemicolonRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie domain'); + } + cookieParts.push('Domain=' + cookie.domain.toLowerCase()); + } + + // RFC 6265, Section 4.1.1 + //'Expires=' sane-cookie-date | Force Date object requirement by using only epoch + if (cookie.expires) { + if (!(cookie.expires instanceof Date)){ + this.reject(500); + throw new Error('Value supplied for cookie "expires" must be a vaild date object'); + } + cookieParts.push('Expires=' + cookie.expires.toGMTString()); + } + + // RFC 6265, Section 4.1.1 + //'Max-Age=' non-zero-digit *DIGIT + if (cookie.maxage) { + var maxage = cookie.maxage; + if (typeof(maxage) === 'string') { + maxage = parseInt(maxage, 10); + } + if (isNaN(maxage) || maxage <= 0 ) { + this.reject(500); + throw new Error('Value supplied for cookie "maxage" must be a non-zero number'); + } + maxage = Math.round(maxage); + cookieParts.push('Max-Age=' + maxage.toString(10)); + } + + // RFC 6265, Section 4.1.1 + //'Secure;' + if (cookie.secure) { + if (typeof(cookie.secure) !== 'boolean') { + this.reject(500); + throw new Error('Value supplied for cookie "secure" must be of type boolean'); + } + cookieParts.push('Secure'); + } + + // RFC 6265, Section 4.1.1 + //'HttpOnly;' + if (cookie.httponly) { + if (typeof(cookie.httponly) !== 'boolean') { + this.reject(500); + throw new Error('Value supplied for cookie "httponly" must be of type boolean'); + } + cookieParts.push('HttpOnly'); + } + + response += ('Set-Cookie: ' + cookieParts.join(';') + '\r\n'); + }.bind(this)); + } + + // TODO: handle negotiated extensions + // if (negotiatedExtensions) { + // response += 'Sec-WebSocket-Extensions: ' + negotiatedExtensions.join(', ') + '\r\n'; + // } + + // Mark the request resolved now so that the user can't call accept or + // reject a second time. + this._resolved = true; + this.emit('requestResolved', this); + + response += '\r\n'; + + var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig); + connection.webSocketVersion = this.webSocketVersion; + connection.remoteAddress = this.remoteAddress; + connection.remoteAddresses = this.remoteAddresses; + + var self = this; + + if (this._socketIsClosing) { + // Handle case when the client hangs up before we get a chance to + // accept the connection and send our side of the opening handshake. + cleanupFailedConnection(connection); + } + else { + this.socket.write(response, 'ascii', function(error) { + if (error) { + cleanupFailedConnection(connection); + return; + } + + self._removeSocketCloseListeners(); + connection._addSocketEventListeners(); + }); + } + + this.emit('requestAccepted', connection); + return connection; +}; + +WebSocketRequest.prototype.reject = function(status, reason, extraHeaders) { + this._verifyResolution(); + + // Mark the request resolved now so that the user can't call accept or + // reject a second time. + this._resolved = true; + this.emit('requestResolved', this); + + if (typeof(status) !== 'number') { + status = 403; + } + var response = 'HTTP/1.1 ' + status + ' ' + httpStatusDescriptions[status] + '\r\n' + + 'Connection: close\r\n'; + if (reason) { + reason = reason.replace(headerSanitizeRegExp, ''); + response += 'X-WebSocket-Reject-Reason: ' + reason + '\r\n'; + } + + if (extraHeaders) { + for (var key in extraHeaders) { + var sanitizedValue = extraHeaders[key].toString().replace(headerSanitizeRegExp, ''); + var sanitizedKey = key.replace(headerSanitizeRegExp, ''); + response += (sanitizedKey + ': ' + sanitizedValue + '\r\n'); + } + } + + response += '\r\n'; + this.socket.end(response, 'ascii'); + + this.emit('requestRejected', this); +}; + +WebSocketRequest.prototype._handleSocketCloseBeforeAccept = function() { + this._socketIsClosing = true; + this._removeSocketCloseListeners(); +}; + +WebSocketRequest.prototype._removeSocketCloseListeners = function() { + this.socket.removeListener('end', this._socketCloseHandler); + this.socket.removeListener('close', this._socketCloseHandler); +}; + +WebSocketRequest.prototype._verifyResolution = function() { + if (this._resolved) { + throw new Error('WebSocketRequest may only be accepted or rejected one time.'); + } +}; + +function cleanupFailedConnection(connection) { + // Since we have to return a connection object even if the socket is + // already dead in order not to break the API, we schedule a 'close' + // event on the connection object to occur immediately. + process.nextTick(function() { + // WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006 + // Third param: Skip sending the close frame to a dead socket + connection.drop(1006, 'TCP connection lost before handshake completed.', true); + }); +} + +module.exports = WebSocketRequest; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouter.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..35bced973e53724530003ef0d393ba70ec299e8d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouter.js @@ -0,0 +1,157 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var extend = require('./utils').extend; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +var WebSocketRouterRequest = require('./WebSocketRouterRequest'); + +function WebSocketRouter(config) { + // Superclass Constructor + EventEmitter.call(this); + + this.config = { + // The WebSocketServer instance to attach to. + server: null + }; + if (config) { + extend(this.config, config); + } + this.handlers = []; + + this._requestHandler = this.handleRequest.bind(this); + if (this.config.server) { + this.attachServer(this.config.server); + } +} + +util.inherits(WebSocketRouter, EventEmitter); + +WebSocketRouter.prototype.attachServer = function(server) { + if (server) { + this.server = server; + this.server.on('request', this._requestHandler); + } + else { + throw new Error('You must specify a WebSocketServer instance to attach to.'); + } +}; + +WebSocketRouter.prototype.detachServer = function() { + if (this.server) { + this.server.removeListener('request', this._requestHandler); + this.server = null; + } + else { + throw new Error('Cannot detach from server: not attached.'); + } +}; + +WebSocketRouter.prototype.mount = function(path, protocol, callback) { + if (!path) { + throw new Error('You must specify a path for this handler.'); + } + if (!protocol) { + protocol = '____no_protocol____'; + } + if (!callback) { + throw new Error('You must specify a callback for this handler.'); + } + + path = this.pathToRegExp(path); + if (!(path instanceof RegExp)) { + throw new Error('Path must be specified as either a string or a RegExp.'); + } + var pathString = path.toString(); + + // normalize protocol to lower-case + protocol = protocol.toLocaleLowerCase(); + + if (this.findHandlerIndex(pathString, protocol) !== -1) { + throw new Error('You may only mount one handler per path/protocol combination.'); + } + + this.handlers.push({ + 'path': path, + 'pathString': pathString, + 'protocol': protocol, + 'callback': callback + }); +}; +WebSocketRouter.prototype.unmount = function(path, protocol) { + var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol); + if (index !== -1) { + this.handlers.splice(index, 1); + } + else { + throw new Error('Unable to find a route matching the specified path and protocol.'); + } +}; + +WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) { + protocol = protocol.toLocaleLowerCase(); + for (var i=0, len=this.handlers.length; i < len; i++) { + var handler = this.handlers[i]; + if (handler.pathString === pathString && handler.protocol === protocol) { + return i; + } + } + return -1; +}; + +WebSocketRouter.prototype.pathToRegExp = function(path) { + if (typeof(path) === 'string') { + if (path === '*') { + path = /^.*$/; + } + else { + path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + path = new RegExp('^' + path + '$'); + } + } + return path; +}; + +WebSocketRouter.prototype.handleRequest = function(request) { + var requestedProtocols = request.requestedProtocols; + if (requestedProtocols.length === 0) { + requestedProtocols = ['____no_protocol____']; + } + + // Find a handler with the first requested protocol first + for (var i=0; i < requestedProtocols.length; i++) { + var requestedProtocol = requestedProtocols[i].toLocaleLowerCase(); + + // find the first handler that can process this request + for (var j=0, len=this.handlers.length; j < len; j++) { + var handler = this.handlers[j]; + if (handler.path.test(request.resourceURL.pathname)) { + if (requestedProtocol === handler.protocol || + handler.protocol === '*') + { + var routerRequest = new WebSocketRouterRequest(request, requestedProtocol); + handler.callback(routerRequest); + return; + } + } + } + } + + // If we get here we were unable to find a suitable handler. + request.reject(404, 'No handler is available for the given request.'); +}; + +module.exports = WebSocketRouter; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..d3e374574ee9c270870033b3f4a413804e843514 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js @@ -0,0 +1,54 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var util = require('util'); +var EventEmitter = require('events').EventEmitter; + +function WebSocketRouterRequest(webSocketRequest, resolvedProtocol) { + // Superclass Constructor + EventEmitter.call(this); + + this.webSocketRequest = webSocketRequest; + if (resolvedProtocol === '____no_protocol____') { + this.protocol = null; + } + else { + this.protocol = resolvedProtocol; + } + this.origin = webSocketRequest.origin; + this.resource = webSocketRequest.resource; + this.resourceURL = webSocketRequest.resourceURL; + this.httpRequest = webSocketRequest.httpRequest; + this.remoteAddress = webSocketRequest.remoteAddress; + this.webSocketVersion = webSocketRequest.webSocketVersion; + this.requestedExtensions = webSocketRequest.requestedExtensions; + this.cookies = webSocketRequest.cookies; +} + +util.inherits(WebSocketRouterRequest, EventEmitter); + +WebSocketRouterRequest.prototype.accept = function(origin, cookies) { + var connection = this.webSocketRequest.accept(this.protocol, origin, cookies); + this.emit('requestAccepted', connection); + return connection; +}; + +WebSocketRouterRequest.prototype.reject = function(status, reason, extraHeaders) { + this.webSocketRequest.reject(status, reason, extraHeaders); + this.emit('requestRejected', this); +}; + +module.exports = WebSocketRouterRequest; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketServer.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketServer.js new file mode 100644 index 0000000000000000000000000000000000000000..c27d967bb26f0fa394cc7374160ccfd95b1d6559 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/WebSocketServer.js @@ -0,0 +1,245 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var extend = require('./utils').extend; +var utils = require('./utils'); +var util = require('util'); +var debug = require('debug')('websocket:server'); +var EventEmitter = require('events').EventEmitter; +var WebSocketRequest = require('./WebSocketRequest'); + +var WebSocketServer = function WebSocketServer(config) { + // Superclass Constructor + EventEmitter.call(this); + + this._handlers = { + upgrade: this.handleUpgrade.bind(this), + requestAccepted: this.handleRequestAccepted.bind(this), + requestResolved: this.handleRequestResolved.bind(this) + }; + this.connections = []; + this.pendingRequests = []; + if (config) { + this.mount(config); + } +}; + +util.inherits(WebSocketServer, EventEmitter); + +WebSocketServer.prototype.mount = function(config) { + this.config = { + // The http server instance to attach to. Required. + httpServer: null, + + // 64KiB max frame size. + maxReceivedFrameSize: 0x10000, + + // 1MiB max message size, only applicable if + // assembleFragments is true + maxReceivedMessageSize: 0x100000, + + // Outgoing messages larger than fragmentationThreshold will be + // split into multiple fragments. + fragmentOutgoingMessages: true, + + // Outgoing frames are fragmented if they exceed this threshold. + // Default is 16KiB + fragmentationThreshold: 0x4000, + + // If true, the server will automatically send a ping to all + // clients every 'keepaliveInterval' milliseconds. The timer is + // reset on any received data from the client. + keepalive: true, + + // The interval to send keepalive pings to connected clients if the + // connection is idle. Any received data will reset the counter. + keepaliveInterval: 20000, + + // If true, the server will consider any connection that has not + // received any data within the amount of time specified by + // 'keepaliveGracePeriod' after a keepalive ping has been sent to + // be dead, and will drop the connection. + // Ignored if keepalive is false. + dropConnectionOnKeepaliveTimeout: true, + + // The amount of time to wait after sending a keepalive ping before + // closing the connection if the connected peer does not respond. + // Ignored if keepalive is false. + keepaliveGracePeriod: 10000, + + // Whether to use native TCP keep-alive instead of WebSockets ping + // and pong packets. Native TCP keep-alive sends smaller packets + // on the wire and so uses bandwidth more efficiently. This may + // be more important when talking to mobile devices. + // If this value is set to true, then these values will be ignored: + // keepaliveGracePeriod + // dropConnectionOnKeepaliveTimeout + useNativeKeepalive: false, + + // If true, fragmented messages will be automatically assembled + // and the full message will be emitted via a 'message' event. + // If false, each frame will be emitted via a 'frame' event and + // the application will be responsible for aggregating multiple + // fragmented frames. Single-frame messages will emit a 'message' + // event in addition to the 'frame' event. + // Most users will want to leave this set to 'true' + assembleFragments: true, + + // If this is true, websocket connections will be accepted + // regardless of the path and protocol specified by the client. + // The protocol accepted will be the first that was requested + // by the client. Clients from any origin will be accepted. + // This should only be used in the simplest of cases. You should + // probably leave this set to 'false' and inspect the request + // object to make sure it's acceptable before accepting it. + autoAcceptConnections: false, + + // Whether or not the X-Forwarded-For header should be respected. + // It's important to set this to 'true' when accepting connections + // from untrusted clients, as a malicious client could spoof its + // IP address by simply setting this header. It's meant to be added + // by a trusted proxy or other intermediary within your own + // infrastructure. + // See: http://en.wikipedia.org/wiki/X-Forwarded-For + ignoreXForwardedFor: false, + + // The Nagle Algorithm makes more efficient use of network resources + // by introducing a small delay before sending small packets so that + // multiple messages can be batched together before going onto the + // wire. This however comes at the cost of latency, so the default + // is to disable it. If you don't need low latency and are streaming + // lots of small messages, you can change this to 'false' + disableNagleAlgorithm: true, + + // The number of milliseconds to wait after sending a close frame + // for an acknowledgement to come back before giving up and just + // closing the socket. + closeTimeout: 5000 + }; + extend(this.config, config); + + if (this.config.httpServer) { + if (!Array.isArray(this.config.httpServer)) { + this.config.httpServer = [this.config.httpServer]; + } + var upgradeHandler = this._handlers.upgrade; + this.config.httpServer.forEach(function(httpServer) { + httpServer.on('upgrade', upgradeHandler); + }); + } + else { + throw new Error('You must specify an httpServer on which to mount the WebSocket server.'); + } +}; + +WebSocketServer.prototype.unmount = function() { + var upgradeHandler = this._handlers.upgrade; + this.config.httpServer.forEach(function(httpServer) { + httpServer.removeListener('upgrade', upgradeHandler); + }); +}; + +WebSocketServer.prototype.closeAllConnections = function() { + this.connections.forEach(function(connection) { + connection.close(); + }); + this.pendingRequests.forEach(function(request) { + process.nextTick(function() { + request.reject(503); // HTTP 503 Service Unavailable + }); + }); +}; + +WebSocketServer.prototype.broadcast = function(data) { + if (Buffer.isBuffer(data)) { + this.broadcastBytes(data); + } + else if (typeof(data.toString) === 'function') { + this.broadcastUTF(data); + } +}; + +WebSocketServer.prototype.broadcastUTF = function(utfData) { + this.connections.forEach(function(connection) { + connection.sendUTF(utfData); + }); +}; + +WebSocketServer.prototype.broadcastBytes = function(binaryData) { + this.connections.forEach(function(connection) { + connection.sendBytes(binaryData); + }); +}; + +WebSocketServer.prototype.shutDown = function() { + this.unmount(); + this.closeAllConnections(); +}; + +WebSocketServer.prototype.handleUpgrade = function(request, socket) { + var wsRequest = new WebSocketRequest(socket, request, this.config); + try { + wsRequest.readHandshake(); + } + catch(e) { + wsRequest.reject( + e.httpCode ? e.httpCode : 400, + e.message, + e.headers + ); + debug('Invalid handshake: %s', e.message); + return; + } + + this.pendingRequests.push(wsRequest); + + wsRequest.once('requestAccepted', this._handlers.requestAccepted); + wsRequest.once('requestResolved', this._handlers.requestResolved); + + if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) { + this.emit('request', wsRequest); + } + else if (this.config.autoAcceptConnections) { + wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin); + } + else { + wsRequest.reject(404, 'No handler is configured to accept the connection.'); + } +}; + +WebSocketServer.prototype.handleRequestAccepted = function(connection) { + var self = this; + connection.once('close', function(closeReason, description) { + self.handleConnectionClose(connection, closeReason, description); + }); + this.connections.push(connection); + this.emit('connect', connection); +}; + +WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) { + var index = this.connections.indexOf(connection); + if (index !== -1) { + this.connections.splice(index, 1); + } + this.emit('close', connection, closeReason, description); +}; + +WebSocketServer.prototype.handleRequestResolved = function(request) { + var index = this.pendingRequests.indexOf(request); + if (index !== -1) { this.pendingRequests.splice(index, 1); } +}; + +module.exports = WebSocketServer; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..c11cea9dd96b1e1fa2e8b2a49fd53cc5796454f1 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/browser.js @@ -0,0 +1,42 @@ +var _global = (function() { return this; })(); +var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; +var websocket_version = require('./version'); + + +/** + * Expose a W3C WebSocket class with just one or two arguments. + */ +function W3CWebSocket(uri, protocols) { + var native_instance; + + if (protocols) { + native_instance = new NativeWebSocket(uri, protocols); + } + else { + native_instance = new NativeWebSocket(uri); + } + + /** + * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket + * class). Since it is an Object it will be returned as it is when creating an + * instance of W3CWebSocket via 'new W3CWebSocket()'. + * + * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 + */ + return native_instance; +} +if (NativeWebSocket) { + ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { + Object.defineProperty(W3CWebSocket, prop, { + get: function() { return NativeWebSocket[prop]; } + }); + }); +} + +/** + * Module exports. + */ +module.exports = { + 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, + 'version' : websocket_version +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/utils.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..6506dc9744007fa5d8bc4c89ba81c1f04a509aef --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/utils.js @@ -0,0 +1,60 @@ +var noop = exports.noop = function(){}; + +exports.extend = function extend(dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } +}; + +exports.eventEmitterListenerCount = + require('events').EventEmitter.listenerCount || + function(emitter, type) { return emitter.listeners(type).length; }; + + + + + +exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) { + var logFunction = require('debug')(identifier); + if (logFunction.enabled) { + var logger = new BufferingLogger(identifier, uniqueID, logFunction); + var debug = logger.log.bind(logger); + debug.printOutput = logger.printOutput.bind(logger); + debug.enabled = logFunction.enabled; + return debug; + } + logFunction.printOutput = noop; + return logFunction; +}; + +function BufferingLogger(identifier, uniqueID, logFunction) { + this.logFunction = logFunction; + this.identifier = identifier; + this.uniqueID = uniqueID; + this.buffer = []; +} + +BufferingLogger.prototype.log = function() { + this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]); + return this; +}; + +BufferingLogger.prototype.clear = function() { + this.buffer = []; + return this; +}; + +BufferingLogger.prototype.printOutput = function(logFunction) { + if (!logFunction) { logFunction = this.logFunction; } + var uniqueID = this.uniqueID; + this.buffer.forEach(function(entry) { + var date = entry[0].toLocaleString(); + var args = entry[1].slice(); + var formatString = args[0]; + if (formatString !== (void 0) && formatString !== null) { + formatString = '%s - %s - ' + formatString.toString(); + args.splice(0, 1, formatString, date, uniqueID); + logFunction.apply(global, args); + } + }); +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/version.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/version.js new file mode 100644 index 0000000000000000000000000000000000000000..81f6e78b6196ee3d29466c59eb870981ba6e2986 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/version.js @@ -0,0 +1 @@ +module.exports = require('../package.json').version; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/websocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..6242d561d916cd502884463f2760fbfada533248 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/lib/websocket.js @@ -0,0 +1,11 @@ +module.exports = { + 'server' : require('./WebSocketServer'), + 'client' : require('./WebSocketClient'), + 'router' : require('./WebSocketRouter'), + 'frame' : require('./WebSocketFrame'), + 'request' : require('./WebSocketRequest'), + 'connection' : require('./WebSocketConnection'), + 'w3cwebsocket' : require('./W3CWebSocket'), + 'deprecation' : require('./Deprecation'), + 'version' : require('./version') +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d805f8dd9b99251128a44de30c622b3acc97e96f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/package.json @@ -0,0 +1,95 @@ +{ + "_from": "websocket", + "_id": "websocket@1.0.25", + "_inBundle": false, + "_integrity": "sha512-M58njvi6ZxVb5k7kpnHh2BvNKuBWiwIYvsToErBzWhvBZYwlEiLcyLrG41T1jRcrY9ettqPYEqduLI7ul54CVQ==", + "_location": "/websocket", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "websocket", + "name": "websocket", + "escapedName": "websocket", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.25.tgz", + "_shasum": "998ec790f0a3eacb8b08b50a4350026692a11958", + "_spec": "websocket", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts", + "author": { + "name": "Brian McKelvey", + "email": "brian@worlize.com", + "url": "https://www.worlize.com/" + }, + "browser": "lib/browser.js", + "bugs": { + "url": "https://github.com/theturtle32/WebSocket-Node/issues" + }, + "bundleDependencies": false, + "config": { + "verbose": false + }, + "contributors": [ + { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net", + "url": "http://dev.sipdoc.net" + } + ], + "dependencies": { + "debug": "^2.2.0", + "nan": "^2.3.3", + "typedarray-to-buffer": "^3.1.2", + "yaeti": "^0.0.6" + }, + "deprecated": false, + "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", + "devDependencies": { + "buffer-equal": "^1.0.0", + "faucet": "^0.0.1", + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jshint": "^2.0.4", + "jshint": "^2.0.0", + "jshint-stylish": "^2.2.1", + "tape": "^4.0.1" + }, + "directories": { + "lib": "./lib" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/theturtle32/WebSocket-Node", + "keywords": [ + "websocket", + "websockets", + "socket", + "networking", + "comet", + "push", + "RFC-6455", + "realtime", + "server", + "client" + ], + "license": "Apache-2.0", + "main": "index", + "name": "websocket", + "repository": { + "type": "git", + "url": "git+https://github.com/theturtle32/WebSocket-Node.git" + }, + "scripts": { + "gulp": "gulp", + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "faucet test/unit" + }, + "version": "1.0.25" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/bufferutil.cc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/bufferutil.cc new file mode 100644 index 0000000000000000000000000000000000000000..d2f8d2d61f29ebf8a712d1b5f1142fa121f63f92 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/bufferutil.cc @@ -0,0 +1,121 @@ +/*! + * BufferUtil originally from: + * ws: a node.js websocket client + * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +#include <v8.h> +#include <node.h> +#include <node_version.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <stdlib.h> +#include <string.h> +#include <wchar.h> +#include <stdio.h> +#include "nan.h" + +using namespace v8; +using namespace node; + +class BufferUtil : public ObjectWrap +{ +public: + + static void Initialize(v8::Handle<v8::Object> target) + { + Nan::HandleScope scope; + Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + Nan::SetMethod(t, "unmask", BufferUtil::Unmask); + Nan::SetMethod(t, "mask", BufferUtil::Mask); + Nan::SetMethod(t, "merge", BufferUtil::Merge); + Nan::Set(target, Nan::New<String>("BufferUtil").ToLocalChecked(), t->GetFunction()); + } + +protected: + + static NAN_METHOD(New) + { + Nan::HandleScope scope; + BufferUtil* bufferUtil = new BufferUtil(); + bufferUtil->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } + + static NAN_METHOD(Merge) + { + Nan::HandleScope scope; + Local<Object> bufferObj = info[0]->ToObject(); + char* buffer = Buffer::Data(bufferObj); + Local<Array> array = Local<Array>::Cast(info[1]); + unsigned int arrayLength = array->Length(); + size_t offset = 0; + unsigned int i; + for (i = 0; i < arrayLength; ++i) { + Local<Object> src = array->Get(i)->ToObject(); + size_t length = Buffer::Length(src); + memcpy(buffer + offset, Buffer::Data(src), length); + offset += length; + } + info.GetReturnValue().Set(Nan::True()); + } + + static NAN_METHOD(Unmask) + { + Nan::HandleScope scope; + Local<Object> buffer_obj = info[0]->ToObject(); + size_t length = Buffer::Length(buffer_obj); + Local<Object> mask_obj = info[1]->ToObject(); + unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); + unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); + size_t len32 = length / 4; + unsigned int i; + for (i = 0; i < len32; ++i) *(from + i) ^= *mask; + from += i; + switch (length % 4) { + case 3: *((unsigned char*)from+2) = *((unsigned char*)from+2) ^ ((unsigned char*)mask)[2]; + case 2: *((unsigned char*)from+1) = *((unsigned char*)from+1) ^ ((unsigned char*)mask)[1]; + case 1: *((unsigned char*)from ) = *((unsigned char*)from ) ^ ((unsigned char*)mask)[0]; + case 0:; + } + info.GetReturnValue().Set(Nan::True()); + } + + static NAN_METHOD(Mask) + { + Nan::HandleScope scope; + Local<Object> buffer_obj = info[0]->ToObject(); + Local<Object> mask_obj = info[1]->ToObject(); + unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); + Local<Object> output_obj = info[2]->ToObject(); + unsigned int dataOffset = info[3]->Int32Value(); + unsigned int length = info[4]->Int32Value(); + unsigned int* to = (unsigned int*)(Buffer::Data(output_obj) + dataOffset); + unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); + unsigned int len32 = length / 4; + unsigned int i; + for (i = 0; i < len32; ++i) *(to + i) = *(from + i) ^ *mask; + to += i; + from += i; + switch (length % 4) { + case 3: *((unsigned char*)to+2) = *((unsigned char*)from+2) ^ *((unsigned char*)mask+2); + case 2: *((unsigned char*)to+1) = *((unsigned char*)from+1) ^ *((unsigned char*)mask+1); + case 1: *((unsigned char*)to ) = *((unsigned char*)from ) ^ *((unsigned char*)mask); + case 0:; + } + info.GetReturnValue().Set(Nan::True()); + } +}; + +#if !NODE_VERSION_AT_LEAST(0,10,0) +extern "C" +#endif +void init (Handle<Object> target) +{ + Nan::HandleScope scope; + BufferUtil::Initialize(target); +} + +NODE_MODULE(bufferutil, init) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/validation.cc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/validation.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e2347e54e79643b4cf1a2aa2b5c15b21d1489af --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/src/validation.cc @@ -0,0 +1,148 @@ +/*! + * UTF-8 Validation Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +#include <v8.h> +#include <node.h> +#include <node_version.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <stdlib.h> +#include <wchar.h> +#include <stdio.h> +#include "nan.h" + +using namespace v8; +using namespace node; + +#define UNI_SUR_HIGH_START (uint32_t) 0xD800 +#define UNI_SUR_LOW_END (uint32_t) 0xDFFF +#define UNI_REPLACEMENT_CHAR (uint32_t) 0x0000FFFD +#define UNI_MAX_LEGAL_UTF32 (uint32_t) 0x0010FFFF + +static const uint8_t trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; + +static const uint32_t offsetsFromUTF8[6] = { + 0x00000000, 0x00003080, 0x000E2080, + 0x03C82080, 0xFA082080, 0x82082080 +}; + +static int isLegalUTF8(const uint8_t *source, const int length) +{ + uint8_t a; + const uint8_t *srcptr = source+length; + switch (length) { + default: return 0; + /* Everything else falls through when "true"... */ + /* RFC3629 makes 5 & 6 bytes UTF-8 illegal + case 6: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 5: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; */ + case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 2: if ((a = (*--srcptr)) > 0xBF) return 0; + switch (*source) { + /* no fall-through in this inner switch */ + case 0xE0: if (a < 0xA0) return 0; break; + case 0xED: if (a > 0x9F) return 0; break; + case 0xF0: if (a < 0x90) return 0; break; + case 0xF4: if (a > 0x8F) return 0; break; + default: if (a < 0x80) return 0; + } + + case 1: if (*source >= 0x80 && *source < 0xC2) return 0; + } + if (*source > 0xF4) return 0; + return 1; +} + +int is_valid_utf8 (size_t len, char *value) +{ + /* is the string valid UTF-8? */ + for (unsigned int i = 0; i < len; i++) { + uint32_t ch = 0; + uint8_t extrabytes = trailingBytesForUTF8[(uint8_t) value[i]]; + + if (extrabytes + i >= len) + return 0; + + if (isLegalUTF8 ((uint8_t *) (value + i), extrabytes + 1) == 0) return 0; + + switch (extrabytes) { + case 5 : ch += (uint8_t) value[i++]; ch <<= 6; + case 4 : ch += (uint8_t) value[i++]; ch <<= 6; + case 3 : ch += (uint8_t) value[i++]; ch <<= 6; + case 2 : ch += (uint8_t) value[i++]; ch <<= 6; + case 1 : ch += (uint8_t) value[i++]; ch <<= 6; + case 0 : ch += (uint8_t) value[i]; + } + + ch -= offsetsFromUTF8[extrabytes]; + + if (ch <= UNI_MAX_LEGAL_UTF32) { + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + return 0; + } else { + return 0; + } + } + + return 1; +} + +class Validation : public ObjectWrap +{ +public: + + static void Initialize(v8::Handle<v8::Object> target) + { + Nan::HandleScope scope; + Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + Nan::SetMethod(t, "isValidUTF8", Validation::IsValidUTF8); + Nan::Set(target, Nan::New<String>("Validation").ToLocalChecked(), t->GetFunction()); + } + +protected: + + static NAN_METHOD(New) + { + Nan::HandleScope scope; + Validation* validation = new Validation(); + validation->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } + + static NAN_METHOD(IsValidUTF8) + { + Nan::HandleScope scope; + if (!Buffer::HasInstance(info[0])) { + return Nan::ThrowTypeError("First argument needs to be a buffer"); + } + Local<Object> buffer_obj = info[0]->ToObject(); + char *buffer_data = Buffer::Data(buffer_obj); + size_t buffer_length = Buffer::Length(buffer_obj); + info.GetReturnValue().Set(is_valid_utf8(buffer_length, buffer_data) == 1 ? Nan::True() : Nan::False()); + } +}; +#if !NODE_VERSION_AT_LEAST(0,10,0) +extern "C" +#endif +void init (Handle<Object> target) +{ + Nan::HandleScope scope; + Validation::Initialize(target); +} + +NODE_MODULE(validation, init) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/vendor/FastBufferList.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/vendor/FastBufferList.js new file mode 100644 index 0000000000000000000000000000000000000000..aabf096a7cc18ba6ed4635a0068cc918645fc1e0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/websocket/vendor/FastBufferList.js @@ -0,0 +1,193 @@ +// This file was copied from https://github.com/substack/node-bufferlist +// and modified to be able to copy bytes from the bufferlist directly into +// a pre-existing fixed-size buffer without an additional memory allocation. + +// bufferlist.js +// Treat a linked list of buffers as a single variable-size buffer. +var Buffer = require('buffer').Buffer; +var EventEmitter = require('events').EventEmitter; + +module.exports = BufferList; +module.exports.BufferList = BufferList; // backwards compatibility + +function BufferList(opts) { + if (!(this instanceof BufferList)) return new BufferList(opts); + EventEmitter.call(this); + var self = this; + + if (typeof(opts) == 'undefined') opts = {}; + + // default encoding to use for take(). Leaving as 'undefined' + // makes take() return a Buffer instead. + self.encoding = opts.encoding; + + // constructor to use for Buffer-esque operations + self.construct = opts.construct || Buffer; + + var head = { next : null, buffer : null }; + var last = { next : null, buffer : null }; + + // length can get negative when advanced past the end + // and this is the desired behavior + var length = 0; + self.__defineGetter__('length', function () { + return length; + }); + + // keep an offset of the head to decide when to head = head.next + var offset = 0; + + // Write to the bufferlist. Emits 'write'. Always returns true. + self.write = function (buf) { + if (!head.buffer) { + head.buffer = buf; + last = head; + } + else { + last.next = { next : null, buffer : buf }; + last = last.next; + } + length += buf.length; + self.emit('write', buf); + return true; + }; + + self.end = function (buf) { + if (Buffer.isBuffer(buf)) self.write(buf); + }; + + // Push buffers to the end of the linked list. (deprecated) + // Return this (self). + self.push = function () { + var args = [].concat.apply([], arguments); + args.forEach(self.write); + return self; + }; + + // For each buffer, perform some action. + // If fn's result is a true value, cut out early. + // Returns this (self). + self.forEach = function (fn) { + if (!head.buffer) return new self.construct(0); + + if (head.buffer.length - offset <= 0) return self; + var firstBuf = head.buffer.slice(offset); + + var b = { buffer : firstBuf, next : head.next }; + + while (b && b.buffer) { + var r = fn(b.buffer); + if (r) break; + b = b.next; + } + + return self; + }; + + // Create a single Buffer out of all the chunks or some subset specified by + // start and one-past the end (like slice) in bytes. + self.join = function (start, end) { + if (!head.buffer) return new self.construct(0); + if (start == undefined) start = 0; + if (end == undefined) end = self.length; + + var big = new self.construct(end - start); + var ix = 0; + self.forEach(function (buffer) { + if (start < (ix + buffer.length) && ix < end) { + // at least partially contained in the range + buffer.copy( + big, + Math.max(0, ix - start), + Math.max(0, start - ix), + Math.min(buffer.length, end - ix) + ); + } + ix += buffer.length; + if (ix > end) return true; // stop processing past end + }); + + return big; + }; + + self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) { + if (!head.buffer) return new self.construct(0); + if (sourceStart == undefined) sourceStart = 0; + if (sourceEnd == undefined) sourceEnd = self.length; + + var big = targetBuffer; + if (big.length - targetStart < sourceEnd - sourceStart) { + throw new Error("Insufficient space available in target Buffer."); + } + var ix = 0; + self.forEach(function (buffer) { + if (sourceStart < (ix + buffer.length) && ix < sourceEnd) { + // at least partially contained in the range + buffer.copy( + big, + Math.max(targetStart, targetStart + ix - sourceStart), + Math.max(0, sourceStart - ix), + Math.min(buffer.length, sourceEnd - ix) + ); + } + ix += buffer.length; + if (ix > sourceEnd) return true; // stop processing past end + }); + + return big; + }; + + // Advance the buffer stream by n bytes. + // If n the aggregate advance offset passes the end of the buffer list, + // operations such as .take() will return empty strings until enough data is + // pushed. + // Returns this (self). + self.advance = function (n) { + offset += n; + length -= n; + while (head.buffer && offset >= head.buffer.length) { + offset -= head.buffer.length; + head = head.next + ? head.next + : { buffer : null, next : null } + ; + } + if (head.buffer === null) last = { next : null, buffer : null }; + self.emit('advance', n); + return self; + }; + + // Take n bytes from the start of the buffers. + // Returns a string. + // If there are less than n bytes in all the buffers or n is undefined, + // returns the entire concatenated buffer string. + self.take = function (n, encoding) { + if (n == undefined) n = self.length; + else if (typeof n !== 'number') { + encoding = n; + n = self.length; + } + var b = head; + if (!encoding) encoding = self.encoding; + if (encoding) { + var acc = ''; + self.forEach(function (buffer) { + if (n <= 0) return true; + acc += buffer.toString( + encoding, 0, Math.min(n,buffer.length) + ); + n -= buffer.length; + }); + return acc; + } else { + // If no 'encoding' is specified, then return a Buffer. + return self.join(0, n); + } + }; + + // The entire concatenated buffer as a string. + self.toString = function () { + return self.take('binary'); + }; +} +require('util').inherits(BufferList, EventEmitter); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a145cd1dff053182c444072e1c199926e0cb09ad --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8f94ca303c5f55dfa355991991b794f9cdf7c1f4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/README.md @@ -0,0 +1,389 @@ +# ws: a Node.js WebSocket library + +[](https://www.npmjs.com/package/ws) +[](https://travis-ci.org/websockets/ws) +[](https://ci.appveyor.com/project/lpinca/ws) +[](https://coveralls.io/r/websockets/ws?branch=master) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client +and server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. +To make the same code work seamlessly on Node.js and the browser, you can use +one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +* [Protocol support](#protocol-support) +* [Installing](#installing) + + [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) +* [API docs](#api-docs) +* [WebSocket compression](#websocket-compression) +* [Usage examples](#usage-examples) + + [Sending and receiving text data](#sending-and-receiving-text-data) + + [Sending binary data](#sending-binary-data) + + [Server example](#server-example) + + [Broadcast example](#broadcast-example) + + [ExpressJS example](#expressjs-example) + + [echo.websocket.org demo](#echowebsocketorg-demo) + + [Other examples](#other-examples) +* [Error handling best practices](#error-handling-best-practices) +* [FAQ](#faq) + + [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + + [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + + [How to connect via a proxy?](#how-to-connect-via-a-proxy) +* [Changelog](#changelog) +* [License](#license) + +## Protocol support + +* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) + +## Installing + +``` +npm install --save ws +``` + +### Opt-in for performance and spec compliance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons which improve certain operations. +Prebuilt binaries are available for the most popular platforms so you don't +necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check + if a message contains valid UTF-8 as required by the spec. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which +enables the client and server to negotiate a compression algorithm and its +parameters, and then selectively apply it to the data payloads of each +WebSocket message. + +The extension is disabled by default on the server and enabled by default on +the client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to +[catastrophic memory fragmentation][node-zlib-bug] and slow performance. +If you intend to use permessage-deflate in production, it is worthwhile to set +up a test representative of your workload and ensure Node.js/zlib will handle +it with acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3, + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + clientMaxWindowBits: 10, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024, // Size (in bytes) below which messages + // should not be compressed. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function incoming(data) { + console.log(data); +}); +``` + +### Sending binary data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Server example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); +``` + +### Broadcast example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +// Broadcast to all. +wss.broadcast = function broadcast(data) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); +}; + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(data) { + // Broadcast to everyone else. + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); + }); +}); +``` + +### ExpressJS example + +```js +const express = require('express'); +const http = require('http'); +const url = require('url'); +const WebSocket = require('ws'); + +const app = express(); + +app.use(function (req, res) { + res.send({ msg: "hello" }); +}); + +const server = http.createServer(app); +const wss = new WebSocket.Server({ server }); + +wss.on('connection', function connection(ws, req) { + const location = url.parse(req.url, true); + // You might use location.query.access_token to authenticate or share sessions + // or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312) + + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); + +server.listen(8080, function listening() { + console.log('Listening on %d', server.address().port); +}); +``` + +### echo.websocket.org demo + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('wss://echo.websocket.org/', { + origin: 'https://websocket.org' +}); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function incoming(data) { + console.log(`Roundtrip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## Error handling best practices + +```js +// If the WebSocket is closed before the following send is attempted +ws.send('something'); + +// Errors (both immediate and async write errors) can be detected in an optional +// callback. The callback is also the only way of being notified that data has +// actually been sent. +ws.send('something', function ack(error) { + // If error is not defined, the send has been completed, otherwise the error + // object will indicate what failed. +}); + +// Immediate errors can also be handled with `try...catch`, but **note** that +// since sends are inherently asynchronous, socket write failures will *not* be +// captured when this technique is used. +try { ws.send('something'); } +catch (e) { /* handle error */ } +``` + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.connection.remoteAddress; +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for']; +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a +way that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +function noop() {} + +function heartbeat() { + this.isAlive = true; +} + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(noop); + }); +}, 30000); +``` + +Pong messages are automatically sent in response to ping messages as required +by the spec. + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[changelog]: https://github.com/websockets/ws/releases +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b8d6be1c9a06bc40ac9ad503a76f3318bc5dade0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +module.exports = WebSocket; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/buffer-util.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000000000000000000000000000000000000..38e16df3f16a3717eeaa00b782346ddb8945f90c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +const concat = (list, totalLength) => { + const target = Buffer.allocUnsafe(totalLength); + var offset = 0; + + for (var i = 0; i < list.length; i++) { + const buf = list[i]; + buf.copy(target, offset); + offset += buf.length; + } + + return target; +}; + +try { + const bufferUtil = require('bufferutil'); + + module.exports = Object.assign({ concat }, bufferUtil.BufferUtil || bufferUtil); +} catch (e) /* istanbul ignore next */ { + /** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ + const mask = (source, mask, output, offset, length) => { + for (var i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + }; + + /** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ + const unmask = (buffer, mask) => { + // Required until https://github.com/nodejs/node/issues/9006 is resolved. + const length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] ^= mask[i & 3]; + } + }; + + module.exports = { concat, mask, unmask }; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/constants.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..4082981f89d2edc44742f51ce0602a5ce9df4bb0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + EMPTY_BUFFER: Buffer.alloc(0), + NOOP: () => {} +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/event-target.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000000000000000000000000000000000000..574e9080e2ee2a90dd67734ab69286336855fbea --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/event-target.js @@ -0,0 +1,170 @@ +'use strict'; + +/** + * Class representing an event. + * + * @private + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @param {Object} target A reference to the target to which the event was dispatched + */ + constructor (type, target) { + this.target = target; + this.type = type; + } +} + +/** + * Class representing a message event. + * + * @extends Event + * @private + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (data, target) { + super('message', target); + + this.data = data; + } +} + +/** + * Class representing a close event. + * + * @extends Event + * @private + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {Number} code The status code explaining why the connection is being closed + * @param {String} reason A human-readable string explaining why the connection is closing + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (code, reason, target) { + super('close', target); + + this.wasClean = target._closeFrameReceived && target._closeFrameSent; + this.reason = reason; + this.code = code; + } +} + +/** + * Class representing an open event. + * + * @extends Event + * @private + */ +class OpenEvent extends Event { + /** + * Create a new `OpenEvent`. + * + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (target) { + super('open', target); + } +} + +/** + * Class representing an error event. + * + * @extends Event + * @private + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {Object} error The error that generated this event + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (error, target) { + super('error', target); + + this.message = error.message; + this.error = error; + } +} + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} method A string representing the event type to listen for + * @param {Function} listener The listener to add + * @public + */ + addEventListener (method, listener) { + if (typeof listener !== 'function') return; + + function onMessage (data) { + listener.call(this, new MessageEvent(data, this)); + } + + function onClose (code, message) { + listener.call(this, new CloseEvent(code, message, this)); + } + + function onError (error) { + listener.call(this, new ErrorEvent(error, this)); + } + + function onOpen () { + listener.call(this, new OpenEvent(this)); + } + + if (method === 'message') { + onMessage._listener = listener; + this.on(method, onMessage); + } else if (method === 'close') { + onClose._listener = listener; + this.on(method, onClose); + } else if (method === 'error') { + onError._listener = listener; + this.on(method, onError); + } else if (method === 'open') { + onOpen._listener = listener; + this.on(method, onOpen); + } else { + this.on(method, listener); + } + }, + + /** + * Remove an event listener. + * + * @param {String} method A string representing the event type to remove + * @param {Function} listener The listener to remove + * @public + */ + removeEventListener (method, listener) { + const listeners = this.listeners(method); + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i] === listener || listeners[i]._listener === listener) { + this.removeListener(method, listeners[i]); + } + } + } +}; + +module.exports = EventTarget; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/extension.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/extension.js new file mode 100644 index 0000000000000000000000000000000000000000..3f48d75174031a06adb47b794e6bcaccbd66fc22 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/extension.js @@ -0,0 +1,211 @@ +'use strict'; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push (dest, name, elem) { + if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem); + else dest[name] = [elem]; +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse (header) { + const offers = {}; + + if (header === undefined || header === '') return offers; + + var params = {}; + var mustUnescape = false; + var isEscaping = false; + var inQuotes = false; + var extensionName; + var paramName; + var start = -1; + var end = -1; + + for (var i = 0; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20/* ' ' */|| code === 0x09/* '\t' */) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b/* ';' */ || code === 0x2c/* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = {}; + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = {}; + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d/* '=' */&& start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22/* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c/* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + var value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = {}; + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, {}); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format (extensions) { + return Object.keys(extensions).map((extension) => { + var configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations.map((params) => { + return [extension].concat(Object.keys(params).map((k) => { + var values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values.map((v) => v === true ? k : `${k}=${v}`).join('; '); + })).join('; '); + }).join(', '); + }).join(', '); +} + +module.exports = { format, parse }; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/permessage-deflate.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..0d54f035b63025c33284a2e02583c17288120c76 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,516 @@ +'use strict'; + +const Limiter = require('async-limiter'); +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const constants = require('./constants'); + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const EMPTY_BLOCK = Buffer.from([0x00]); + +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kWriteInProgress = Symbol('write-in-progress'); +const kPendingClose = Symbol('pending-close'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} options Configuration options + * @param {Boolean} options.serverNoContextTakeover Request/accept disabling + * of server context takeover + * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge + * disabling of client context takeover + * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the + * use of a custom server window size + * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support + * for, or request, a custom client window size + * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate + * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate + * @param {Number} options.threshold Size (in bytes) below which messages + * should not be compressed + * @param {Number} options.concurrencyLimit The number of concurrent calls to + * zlib + * @param {Boolean} isServer Create the instance in either server or client + * mode + * @param {Number} maxPayload The maximum allowed message length + */ + constructor (options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = this._options.threshold !== undefined + ? this._options.threshold + : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter({ concurrency }); + } + } + + /** + * @type {String} + */ + static get extensionName () { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer () { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept (configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup () { + if (this._inflate) { + if (this._inflate[kWriteInProgress]) { + this._inflate[kPendingClose] = true; + } else { + this._inflate.close(); + this._inflate = null; + } + } + if (this._deflate) { + if (this._deflate[kWriteInProgress]) { + this._deflate[kPendingClose] = true; + } else { + this._deflate.close(); + this._deflate = null; + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer (offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient (response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams (configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + var value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited by async-limiter. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress (data, fin, callback) { + zlibLimiter.push((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited by async-limiter. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress (data, fin, callback) { + zlibLimiter.push((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress (data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw( + Object.assign({}, this._options.zlibInflateOptions, { windowBits }) + ); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + this._inflate[kWriteInProgress] = true; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._inflate[kPendingClose] + ) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kWriteInProgress] = false; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress (data, fin, callback) { + if (!data || data.length === 0) { + process.nextTick(callback, null, EMPTY_BLOCK); + return; + } + + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw( + Object.assign( + // TODO deprecate memLevel/level and recommend zlibDeflateOptions instead + { + memLevel: this._options.memLevel, + level: this._options.level + }, + this._options.zlibDeflateOptions, + { windowBits } + ) + ); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + // + // `zlib.DeflateRaw` emits an `'error'` event only when an attempt to use + // it is made after it has already been closed. This cannot happen here, + // so we only add a listener for the `'data'` event. + // + this._deflate.on('data', deflateOnData); + } + + this._deflate[kWriteInProgress] = true; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + var data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) data = data.slice(0, data.length - 4); + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._deflate[kPendingClose] + ) { + this._deflate.close(); + this._deflate = null; + } else { + this._deflate[kWriteInProgress] = false; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData (chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData (chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError][constants.kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError (err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[constants.kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/receiver.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000000000000000000000000000000000000..ab2d68c8d420889027b997fb3af01c02ec0ca3ff --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/receiver.js @@ -0,0 +1,513 @@ +'use strict'; + +const stream = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const bufferUtil = require('./buffer-util'); +const validation = require('./validation'); +const constants = require('./constants'); + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends stream.Writable + */ +class Receiver extends stream.Writable { + /** + * Creates a Receiver instance. + * + * @param {String} binaryType The type for binary data + * @param {Object} extensions An object containing the negotiated extensions + * @param {Number} maxPayload The maximum allowed message length + */ + constructor (binaryType, extensions, maxPayload) { + super(); + + this._binaryType = binaryType || constants.BINARY_TYPES[0]; + this[constants.kWebSocket] = undefined; + this._extensions = extensions || {}; + this._maxPayload = maxPayload | 0; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + */ + _write (chunk, encoding, cb) { + if (this._opcode === 0x08) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume (n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + + if (n >= buf.length) { + this._buffers.shift().copy(dst, dst.length - n); + } else { + buf.copy(dst, dst.length - n, 0, n); + this._buffers[0] = buf.slice(n); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop (cb) { + var err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo () { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + if (!this._fragmented) { + this._loop = false; + return error(RangeError, 'invalid opcode 0', true, 1002); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error(RangeError, 'FIN must be set', true, 1002); + } + + if (compressed) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + if (this._payloadLength > 0x7d) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002 + ); + } + } else { + this._loop = false; + return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16 () { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0, true); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64 () { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0, true); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009 + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4, true); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength () { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error(RangeError, 'Max payload size exceeded', false, 1009); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask () { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData (cb) { + var data = constants.EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + if (this._masked) bufferUtil.unmask(data, this._mask); + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its lenght is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress (data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb(error(RangeError, 'Max payload size exceeded', false, 1009)); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage () { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + var data; + + if (this._binaryType === 'nodebuffer') { + data = toBuffer(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(toBuffer(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data); + } else { + const buf = toBuffer(fragments, messageLength); + + if (!validation.isValidUTF8(buf)) { + this._loop = false; + return error(Error, 'invalid UTF-8 sequence', true, 1007); + } + + this.emit('message', buf.toString()); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage (data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, ''); + this.end(); + } else if (data.length === 1) { + return error(RangeError, 'invalid payload length 1', true, 1002); + } else { + const code = data.readUInt16BE(0, true); + + if (!validation.isValidStatusCode(code)) { + return error(RangeError, `invalid status code ${code}`, true, 1002); + } + + const buf = data.slice(2); + + if (!validation.isValidUTF8(buf)) { + return error(Error, 'invalid UTF-8 sequence', true, 1007); + } + + this.emit('conclude', code, buf.toString()); + this.end(); + } + + return; + } + + if (this._opcode === 0x09) this.emit('ping', data); + else this.emit('pong', data); + + this._state = GET_INFO; + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {(Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @return {(Error|RangeError)} The error + * @private + */ +function error (ErrorCtor, message, prefix, statusCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err[constants.kStatusCode] = statusCode; + return err; +} + +/** + * Makes a buffer from a list of fragments. + * + * @param {Buffer[]} fragments The list of fragments composing the message + * @param {Number} messageLength The length of the message + * @return {Buffer} + * @private + */ +function toBuffer (fragments, messageLength) { + if (fragments.length === 1) return fragments[0]; + if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength); + return constants.EMPTY_BUFFER; +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} The buffer to convert + * @return {ArrayBuffer} Converted buffer + */ +function toArrayBuffer (buf) { + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/sender.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/sender.js new file mode 100644 index 0000000000000000000000000000000000000000..42cbb890f6e7b41d074eb44bda06a12fb6869f58 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/sender.js @@ -0,0 +1,401 @@ +'use strict'; + +const crypto = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const bufferUtil = require('./buffer-util'); +const validation = require('./validation'); +const constants = require('./constants'); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {net.Socket} socket The connection socket + * @param {Object} extensions An object containing the negotiated extensions + */ + constructor (socket, extensions) { + this._extensions = extensions || {}; + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {Buffer} data The data to frame + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @return {Buffer[]} The framed data as a list of `Buffer` instances + * @public + */ + static frame (data, options) { + const merge = data.length < 1024 || (options.mask && options.readOnly); + var offset = options.mask ? 6 : 2; + var payloadLength = data.length; + + if (data.length >= 65536) { + offset += 8; + payloadLength = 127; + } else if (data.length > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + if (payloadLength === 126) { + target.writeUInt16BE(data.length, 2, true); + } else if (payloadLength === 127) { + target.writeUInt32BE(0, 2, true); + target.writeUInt32BE(data.length, 6, true); + } + + if (!options.mask) { + target[1] = payloadLength; + if (merge) { + data.copy(target, offset); + return [target]; + } + + return [target, data]; + } + + const mask = crypto.randomBytes(4); + + target[1] = payloadLength | 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (merge) { + bufferUtil.mask(data, mask, target, offset, data.length); + return [target]; + } + + bufferUtil.mask(data, mask, data, 0, data.length); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {(Number|undefined)} code The status code component of the body + * @param {String} data The message component of the body + * @param {Boolean} mask Specifies whether or not to mask the message + * @param {Function} cb Callback + * @public + */ + close (code, data, mask, cb) { + var buf; + + if (code === undefined) { + buf = constants.EMPTY_BUFFER; + } else if (typeof code !== 'number' || !validation.isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || data === '') { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0, true); + } else { + buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data)); + buf.writeUInt16BE(code, 0, true); + buf.write(data, 2); + } + + if (this._deflating) { + this.enqueue([this.doClose, buf, mask, cb]); + } else { + this.doClose(buf, mask, cb); + } + } + + /** + * Frames and sends a close message. + * + * @param {Buffer} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @private + */ + doClose (data, mask, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x08, + mask, + readOnly: false + }), cb); + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + ping (data, mask, cb) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this._deflating) { + this.enqueue([this.doPing, data, mask, readOnly, cb]); + } else { + this.doPing(data, mask, readOnly, cb); + } + } + + /** + * Frames and sends a ping message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @param {Function} cb Callback + * @private + */ + doPing (data, mask, readOnly, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x09, + mask, + readOnly + }), cb); + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + pong (data, mask, cb) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this._deflating) { + this.enqueue([this.doPong, data, mask, readOnly, cb]); + } else { + this.doPong(data, mask, readOnly, cb); + } + } + + /** + * Frames and sends a pong message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @param {Function} cb Callback + * @private + */ + doPong (data, mask, readOnly, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x0a, + mask, + readOnly + }), cb); + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + send (data, options, cb) { + var opcode = options.binary ? 2 : 1; + var rsv1 = options.compress; + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate) { + rsv1 = data.length >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + fin: options.fin, + rsv1, + opcode, + mask: options.mask, + readOnly + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame(Sender.frame(data, { + fin: options.fin, + rsv1: false, + opcode, + mask: options.mask, + readOnly + }), cb); + } + } + + /** + * Dispatches a data message. + * + * @param {Buffer} data The message to send + * @param {Boolean} compress Specifies whether or not to compress `data` + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @param {Function} cb Callback + * @private + */ + dispatch (data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this._deflating = false; + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue () { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[1].length; + params[0].apply(this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue (params) { + this._bufferedBytes += params[1].length; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} cb Callback + * @private + */ + sendFrame (list, cb) { + if (list.length === 2) { + this._socket.write(list[0]); + this._socket.write(list[1], cb); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Converts an `ArrayBuffer` view into a buffer. + * + * @param {(DataView|TypedArray)} view The view to convert + * @return {Buffer} Converted view + * @private + */ +function viewToBuffer (view) { + const buf = Buffer.from(view.buffer); + + if (view.byteLength !== view.buffer.byteLength) { + return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); + } + + return buf; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/validation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..06269fcf1ae7838387a31ed9fdd9ba7056c50e8b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/validation.js @@ -0,0 +1,29 @@ +'use strict'; + +try { + const isValidUTF8 = require('utf-8-validate'); + + exports.isValidUTF8 = typeof isValidUTF8 === 'object' + ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0 + : isValidUTF8; +} catch (e) /* istanbul ignore next */ { + exports.isValidUTF8 = () => true; +} + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +exports.isValidStatusCode = (code) => { + return ( + (code >= 1000 && + code <= 1013 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket-server.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000000000000000000000000000000000000..72618d02876c84f085aef2e8a855d850691b3c5f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,350 @@ +'use strict'; + +const EventEmitter = require('events'); +const crypto = require('crypto'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const extension = require('./extension'); +const constants = require('./constants'); +const WebSocket = require('./websocket'); + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {String} options.host The hostname where to bind the server + * @param {Number} options.port The port where to bind the server + * @param {http.Server} options.server A pre-created HTTP/S server to use + * @param {Function} options.verifyClient An hook to reject connections + * @param {Function} options.handleProtocols An hook to handle protocols + * @param {String} options.path Accept only connections matching this path + * @param {Boolean} options.noServer Enable no server mode + * @param {Boolean} options.clientTracking Specifies whether or not to track clients + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {Number} options.maxPayload The maximum allowed message size + * @param {Function} callback A listener for the `listening` event + */ + constructor (options, callback) { + super(); + + options = Object.assign({ + maxPayload: 100 * 1024 * 1024, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null + }, options); + + if (options.port == null && !options.server && !options.noServer) { + throw new TypeError( + 'One of the "port", "server", or "noServer" options must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen(options.port, options.host, options.backlog, callback); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, (ws) => { + this.emit('connection', ws, req); + }); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) this.clients = new Set(); + this.options = options; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address () { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Close the server. + * + * @param {Function} cb Callback + * @public + */ + close (cb) { + // + // Terminate all associated clients. + // + if (this.clients) { + for (const client of this.clients) client.terminate(); + } + + const server = this._server; + + if (server) { + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // Close the http server if it was internally created. + // + if (this.options.port != null) return server.close(cb); + } + + if (cb) cb(); + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle (req) { + if (this.options.path && url.parse(req.url).pathname !== this.options.path) { + return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade (req, socket, head, cb) { + socket.on('error', socketOnError); + + const version = +req.headers['sec-websocket-version']; + const extensions = {}; + + if ( + req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) || + !this.shouldHandle(req) + ) { + return abortHandshake(socket, 400); + } + + if (this.options.perMessageDeflate) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse( + req.headers['sec-websocket-extensions'] + ); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + return abortHandshake(socket, 400); + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.connection.authorized || req.connection.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message) => { + if (!verified) return abortHandshake(socket, code || 401, message); + + this.completeUpgrade(extensions, req, socket, head, cb); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @private + */ + completeUpgrade (extensions, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + const key = crypto.createHash('sha1') + .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary') + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${key}` + ]; + + const ws = new WebSocket(null); + var protocol = req.headers['sec-websocket-protocol']; + + if (protocol) { + protocol = protocol.trim().split(/ *, */); + + // + // Optionally call external protocol selection handler. + // + if (this.options.handleProtocols) { + protocol = this.options.handleProtocols(protocol, req); + } else { + protocol = protocol[0]; + } + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws.protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, this.options.maxPayload); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => this.clients.delete(ws)); + } + + cb(ws); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of <event, listener> + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.<String, Function>} map The listeners to add + * @return {Function} A function that will remove the added listeners when called + * @private + */ +function addListeners (server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners () { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Handle premature socket errors. + * + * @private + */ +function socketOnError () { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {net.Socket} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @private + */ +function abortHandshake (socket, code, message) { + if (socket.writable) { + message = message || http.STATUS_CODES[code]; + socket.write( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + 'Connection: close\r\n' + + 'Content-type: text/html\r\n' + + `Content-Length: ${Buffer.byteLength(message)}\r\n` + + '\r\n' + + message + ); + } + + socket.removeListener('error', socketOnError); + socket.destroy(); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..87f3606fb2ac81d1ad2dca28e295e1316654a3b1 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/lib/websocket.js @@ -0,0 +1,844 @@ +'use strict'; + +const EventEmitter = require('events'); +const crypto = require('crypto'); +const https = require('https'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const EventTarget = require('./event-target'); +const extension = require('./extension'); +const constants = require('./constants'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); + +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const kWebSocket = constants.kWebSocket; +const protocolVersions = [8, 13]; +const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly. + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {String} address The URL to which to connect + * @param {(String|String[])} protocols The subprotocols + * @param {Object} options Connection options + */ + constructor (address, protocols, options) { + super(); + + this.readyState = WebSocket.CONNECTING; + this.protocol = ''; + + this._binaryType = constants.BINARY_TYPES[0]; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = ''; + this._closeTimer = null; + this._closeCode = 1006; + this._extensions = {}; + this._isServer = true; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + if (!protocols) { + protocols = []; + } else if (typeof protocols === 'string') { + protocols = [protocols]; + } else if (!Array.isArray(protocols)) { + options = protocols; + protocols = []; + } + + initAsClient.call(this, address, protocols, options); + } + } + + get CONNECTING () { return WebSocket.CONNECTING; } + get CLOSING () { return WebSocket.CLOSING; } + get CLOSED () { return WebSocket.CLOSED; } + get OPEN () { return WebSocket.OPEN; } + + /** + * This deviates from the WHATWG interface since ws doesn't support the required + * default "blob" type (instead we define a custom "nodebuffer" type). + * + * @type {String} + */ + get binaryType () { + return this._binaryType; + } + + set binaryType (type) { + if (constants.BINARY_TYPES.indexOf(type) < 0) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount () { + if (!this._socket) return 0; + + // + // `socket.bufferSize` is `undefined` if the socket is closed. + // + return (this._socket.bufferSize || 0) + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions () { + return Object.keys(this._extensions).join(); + } + + /** + * Set up the socket and the internal resources. + * + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Number} maxPayload The maximum allowed message size + * @private + */ + setSocket (socket, head, maxPayload) { + const receiver = new Receiver( + this._binaryType, + this._extensions, + maxPayload + ); + + this._sender = new Sender(socket, this._extensions); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this.readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose () { + this.readyState = WebSocket.CLOSED; + + if (!this._socket) { + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} code Status code explaining why the connection is closing + * @param {String} data A string explaining why the connection is closing + * @public + */ + close (code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this.readyState === WebSocket.CLOSING) { + if (this._closeFrameSent && this._closeFrameReceived) this._socket.end(); + return; + } + + this.readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if (this._socket.writable) { + if (this._closeFrameReceived) this._socket.end(); + + // + // Ensure that the connection is closed even if the closing handshake + // fails. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + }); + } + + /** + * Send a ping. + * + * @param {*} data The data to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Function} cb Callback which is executed when the ping is sent + * @public + */ + ping (data, mask, cb) { + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || constants.EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} data The data to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Function} cb Callback which is executed when the pong is sent + * @public + */ + pong (data, mask, cb) { + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || constants.EMPTY_BUFFER, mask, cb); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback which is executed when data is written out + * @public + */ + send (data, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + + const opts = Object.assign({ + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true + }, options); + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || constants.EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate () { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this._socket) { + this.readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +readyStates.forEach((readyState, i) => { + WebSocket[readyStates[i]] = i; +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + /** + * Return the listener of the event. + * + * @return {(Function|undefined)} The event listener or `undefined` + * @public + */ + get () { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + if (listeners[i]._listener) return listeners[i]._listener; + } + }, + /** + * Add a listener for the event. + * + * @param {Function} listener The listener to add + * @public + */ + set (listener) { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + // + // Remove only the listeners added via `addEventListener`. + // + if (listeners[i]._listener) this.removeListener(method, listeners[i]); + } + this.addEventListener(method, listener); + } + }); +}); + +WebSocket.prototype.addEventListener = EventTarget.addEventListener; +WebSocket.prototype.removeEventListener = EventTarget.removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {String} address The URL to which to connect + * @param {String[]} protocols The list of subprotocols + * @param {Object} options Connection options + * @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request + * @param {String} options.localAddress Local interface to bind for network connections + * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header + * @param {Object} options.headers An object containing request headers + * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header + * @param {http.Agent} options.agent Use the specified Agent + * @param {String} options.host Value of the `Host` header + * @param {Number} options.family IP address family to use during hostname lookup (4 or 6). + * @param {Function} options.checkServerIdentity A function to validate the server hostname + * @param {Boolean} options.rejectUnauthorized Verify or not the server certificate + * @param {String} options.passphrase The passphrase for the private key or pfx + * @param {String} options.ciphers The ciphers to use or exclude + * @param {String} options.ecdhCurve The curves for ECDH key agreement to use or exclude + * @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key + * @param {(String|String[]|Buffer|Buffer[])} options.key The private key + * @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs + * @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates + * @private + */ +function initAsClient (address, protocols, options) { + options = Object.assign({ + protocolVersion: protocolVersions[1], + protocol: protocols.join(','), + perMessageDeflate: true, + handshakeTimeout: null, + localAddress: null, + headers: null, + family: null, + origin: null, + agent: null, + host: null, + + // + // SSL options. + // + checkServerIdentity: null, + rejectUnauthorized: null, + passphrase: null, + ciphers: null, + ecdhCurve: null, + cert: null, + key: null, + pfx: null, + ca: null + }, options); + + if (protocolVersions.indexOf(options.protocolVersion) === -1) { + throw new RangeError( + `Unsupported protocol version: ${options.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + this._isServer = false; + this.url = address; + + const serverUrl = url.parse(address); + const isUnixSocket = serverUrl.protocol === 'ws+unix:'; + + if (!serverUrl.host && (!isUnixSocket || !serverUrl.path)) { + throw new Error(`Invalid URL: ${address}`); + } + + const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:'; + const key = crypto.randomBytes(16).toString('base64'); + const httpObj = isSecure ? https : http; + var perMessageDeflate; + + const requestOptions = { + port: serverUrl.port || (isSecure ? 443 : 80), + host: serverUrl.hostname, + path: '/', + headers: { + 'Sec-WebSocket-Version': options.protocolVersion, + 'Sec-WebSocket-Key': key, + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; + + if (options.headers) Object.assign(requestOptions.headers, options.headers); + if (options.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + options.perMessageDeflate !== true ? options.perMessageDeflate : {}, + false + ); + requestOptions.headers['Sec-WebSocket-Extensions'] = extension.format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (options.protocol) { + requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol; + } + if (options.origin) { + if (options.protocolVersion < 13) { + requestOptions.headers['Sec-WebSocket-Origin'] = options.origin; + } else { + requestOptions.headers.Origin = options.origin; + } + } + if (options.host) requestOptions.headers.Host = options.host; + if (serverUrl.auth) requestOptions.auth = serverUrl.auth; + + if (options.localAddress) requestOptions.localAddress = options.localAddress; + if (options.family) requestOptions.family = options.family; + + if (isUnixSocket) { + const parts = serverUrl.path.split(':'); + + requestOptions.socketPath = parts[0]; + requestOptions.path = parts[1]; + } else if (serverUrl.path) { + // + // Make sure that path starts with `/`. + // + if (serverUrl.path.charAt(0) !== '/') { + requestOptions.path = `/${serverUrl.path}`; + } else { + requestOptions.path = serverUrl.path; + } + } + + var agent = options.agent; + + // + // A custom agent is required for these options. + // + if ( + options.rejectUnauthorized != null || + options.checkServerIdentity || + options.passphrase || + options.ciphers || + options.ecdhCurve || + options.cert || + options.key || + options.pfx || + options.ca + ) { + if (options.passphrase) requestOptions.passphrase = options.passphrase; + if (options.ciphers) requestOptions.ciphers = options.ciphers; + if (options.ecdhCurve) requestOptions.ecdhCurve = options.ecdhCurve; + if (options.cert) requestOptions.cert = options.cert; + if (options.key) requestOptions.key = options.key; + if (options.pfx) requestOptions.pfx = options.pfx; + if (options.ca) requestOptions.ca = options.ca; + if (options.checkServerIdentity) { + requestOptions.checkServerIdentity = options.checkServerIdentity; + } + if (options.rejectUnauthorized != null) { + requestOptions.rejectUnauthorized = options.rejectUnauthorized; + } + + if (!agent) agent = new httpObj.Agent(requestOptions); + } + + if (agent) requestOptions.agent = agent; + + var req = this._req = httpObj.get(requestOptions); + + if (options.handshakeTimeout) { + req.setTimeout( + options.handshakeTimeout, + abortHandshake.bind(null, this, req, 'Opening handshake has timed out') + ); + } + + req.on('error', (err) => { + if (this._req.aborted) return; + + req = this._req = null; + this.readyState = WebSocket.CLOSING; + this.emit('error', err); + this.emitClose(); + }); + + req.on('response', (res) => { + if (this.emit('unexpected-response', req, res)) return; + + abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`); + }); + + req.on('upgrade', (res, socket, head) => { + this.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the `upgrade` + // event. + // + if (this.readyState !== WebSocket.CONNECTING) return; + + req = this._req = null; + + const digest = crypto.createHash('sha1') + .update(key + constants.GUID, 'binary') + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + const protList = (options.protocol || '').split(/, */); + var protError; + + if (!options.protocol && serverProt) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (options.protocol && !serverProt) { + protError = 'Server sent no subprotocol'; + } else if (serverProt && protList.indexOf(serverProt) === -1) { + protError = 'Server sent an invalid subprotocol'; + } + + if (protError) { + abortHandshake(this, socket, protError); + return; + } + + if (serverProt) this.protocol = serverProt; + + if (perMessageDeflate) { + try { + const extensions = extension.parse( + res.headers['sec-websocket-extensions'] + ); + + if (extensions[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept( + extensions[PerMessageDeflate.extensionName] + ); + this._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header'); + return; + } + } + + this.setSocket(socket, head, 0); + }); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the + * socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake (websocket, stream, message) { + websocket.readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream.abort(); + stream.once('abort', websocket.emitClose.bind(websocket)); + websocket.emit('error', err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {String} reason The reason for closing + * @private + */ +function receiverOnConclude (code, reason) { + const websocket = this[kWebSocket]; + + websocket._socket.removeListener('data', socketOnData); + websocket._socket.resume(); + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain () { + this[kWebSocket]._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError (err) { + const websocket = this[kWebSocket]; + + websocket.readyState = WebSocket.CLOSING; + websocket._closeCode = err[constants.kStatusCode]; + websocket.emit('error', err); + websocket._socket.destroy(); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish () { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message + * @private + */ +function receiverOnMessage (data) { + this[kWebSocket].emit('message', data); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing (data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, constants.NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong (data) { + this[kWebSocket].emit('pong', data); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose () { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + this[kWebSocket] = undefined; + + websocket.readyState = WebSocket.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. + // + websocket._socket.read(); + websocket._receiver.end(); + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData (chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd () { + const websocket = this[kWebSocket]; + + websocket.readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError () { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', constants.NOOP); + + if (websocket) { + websocket.readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/package.json new file mode 100644 index 0000000000000000000000000000000000000000..50adda8a2f659d7f48045cb5585567d03cfdf41c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/ws/package.json @@ -0,0 +1,79 @@ +{ + "_from": "ws", + "_id": "ws@5.0.0", + "_inBundle": false, + "_integrity": "sha512-XXG4S0b771C68AeTHebBsJJBZMguxj7Em+D657RViuj6ppRd3tfuOhIK8eGwZGNb76C8MjQfCTfH2NN50rJN4w==", + "_location": "/ws", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "ws", + "name": "ws", + "escapedName": "ws", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/ws/-/ws-5.0.0.tgz", + "_shasum": "fb4ede3fddcff99b157d292a1069ace8d6e04db9", + "_spec": "ws", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts", + "author": { + "name": "Einar Otto Stangvik", + "email": "einaros@gmail.com", + "url": "http://2x.io" + }, + "bugs": { + "url": "https://github.com/websockets/ws/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async-limiter": "~1.0.0" + }, + "deprecated": false, + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "devDependencies": { + "benchmark": "~2.1.2", + "bufferutil": "~3.0.0", + "eslint": "~4.18.0", + "eslint-config-standard": "~11.0.0", + "eslint-plugin-import": "~2.9.0", + "eslint-plugin-node": "~6.0.0", + "eslint-plugin-promise": "~3.6.0", + "eslint-plugin-standard": "~3.0.0", + "mocha": "~5.0.0", + "nyc": "~11.4.1", + "utf-8-validate": "~4.0.0" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/websockets/ws", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "license": "MIT", + "main": "index.js", + "name": "ws", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "scripts": { + "integration": "eslint . && mocha test/*.integration.js", + "lint": "eslint .", + "test": "eslint . && nyc --reporter=html --reporter=text mocha test/*.test.js" + }, + "version": "5.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jscsrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jscsrc new file mode 100644 index 0000000000000000000000000000000000000000..a37d119c4261591c5c01fc61cf2c871fa010b755 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jscsrc @@ -0,0 +1,6 @@ +{ + "preset": "crockford", + "validateIndentation": "\t", + "disallowKeywords": ["with"], + "disallowDanglingUnderscores": null +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jshintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..1cca0fab33f000c0e8a8a7c4bc1230d93755cf6c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.jshintrc @@ -0,0 +1,27 @@ +{ + "bitwise": false, + "curly": true, + "eqeqeq": true, + "forin": true, + "freeze": true, + "latedef": "function", + "noarg": true, + "nonbsp": true, + "nonew": true, + "plusplus": false, + "undef": true, + "unused": true, + "strict": false, + "maxparams": 6, + "maxdepth": 4, + "maxstatements": false, + "maxlen": 200, + "browser": true, + "browserify": true, + "devel": true, + "jquery": false, + "mocha": true, + "node": false, + "shelljs": false, + "worker": false +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.npmignore b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..2ccbe4656c6078ded72491cf2ee9c5ec20219624 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/.npmignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a64a4125c18ba58ffa871adcc338b0a8311a96e7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Iñaki Baz Castillo, <ibc@aliax.net> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/README.md new file mode 100644 index 0000000000000000000000000000000000000000..db253a4375d5eecdcc4640e1d41db9d9e4ba7ce3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/README.md @@ -0,0 +1,98 @@ +# yaeti + +Yet Another [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) Implementation. + +The library exposes both the [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) interface and the [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface. + + +## Installation + +```bash +$ npm install yaeti --save +``` + + +## Usage + +```javascript +var yaeti = require('yaeti'); + + +// Custom class we want to make an EventTarget. +function Foo() { + // Make Foo an EventTarget. + yaeti.EventTarget.call(this); +} + +// Create an instance. +var foo = new Foo(); + +function listener1() { + console.log('listener1'); +} + +function listener2() { + console.log('listener2'); +} + +foo.addEventListener('bar', listener1); +foo.addEventListener('bar', listener2); +foo.removeEventListener('bar', listener1); + +var event = new yaeti.Event('bar'); + +foo.dispatchEvent(event); + + +// Output: +// => "listener2" +``` + + + +## API + + +#### `yaeti.EventTarget` interface + +Implementation of the [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) interface. + +* Make a custom class inherit from `EventTarget`: +```javascript +function Foo() { + yaeti.EventTarget.call(this); +} +``` + +* Make an existing object an `EventTarget`: +```javascript +yaeti.EventTarget.call(obj); +``` + +The interface implements the `addEventListener`, `removeEventListener` and `dispatchEvent` methods as defined by the W3C. + + +##### `listeners` read-only property + +Returns an object whose keys are configured event types (String) and whose values are an array of listeners (functions) for those event types. + + +#### `yaeti.Event` interface + +Implementation of the [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface. + +*NOTE:* Just useful in Node (the browser already exposes the native `Event` interface). + +```javascript +var event = new yaeti.Event('bar'); +``` + + +## Author + +[Iñaki Baz Castillo](https://github.com/ibc) + + +## License + +[MIT](./LICENSE) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/gulpfile.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..294cd9c7c05a3cd10c1e19bf0a97611eb6202f55 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/gulpfile.js @@ -0,0 +1,23 @@ +var + /** + * Dependencies. + */ + gulp = require('gulp'), + jscs = require('gulp-jscs'), + jshint = require('gulp-jshint'), + stylish = require('gulp-jscs-stylish'); + + +gulp.task('lint', function () { + var src = ['gulpfile.js', 'index.js', 'lib/**/*.js']; + + return gulp.src(src) + .pipe(jshint('.jshintrc')) // Enforce good practics. + .pipe(jscs('.jscsrc')) // Enforce style guide. + .pipe(stylish.combineWithHintResults()) + .pipe(jshint.reporter('jshint-stylish', {verbose: true})) + .pipe(jshint.reporter('fail')); +}); + + +gulp.task('default', gulp.task('lint')); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b1e6db47e276e09ae1c0b8cbb2ba0357628b3cb7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/index.js @@ -0,0 +1,4 @@ +module.exports = { + EventTarget : require('./lib/EventTarget'), + Event : require('./lib/Event') +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..0cd5ea68aeb0f9962991a6cc4659af7a6bfceab7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.browser.js @@ -0,0 +1,5 @@ +/** + * In browsers export the native Event interface. + */ + +module.exports = global.Event; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.js new file mode 100644 index 0000000000000000000000000000000000000000..cd245a27a46f7fc0f8f7805dc9124d5e089cbf58 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/Event.js @@ -0,0 +1,13 @@ +/** + * Expose the Event class. + */ +module.exports = _Event; + + +function _Event(type) { + this.type = type; + this.isTrusted = false; + + // Set a flag indicating this is not a DOM Event object + this._yaeti = true; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/EventTarget.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/EventTarget.js new file mode 100644 index 0000000000000000000000000000000000000000..403c75bd4e3a6b6dff6ba8a865d3b6292793f985 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/lib/EventTarget.js @@ -0,0 +1,119 @@ +/** + * Expose the _EventTarget class. + */ +module.exports = _EventTarget; + +function _EventTarget() { + // Do nothing if called for a native EventTarget object.. + if (typeof this.addEventListener === 'function') { + return; + } + + this._listeners = {}; + + this.addEventListener = _addEventListener; + this.removeEventListener = _removeEventListener; + this.dispatchEvent = _dispatchEvent; +} + +Object.defineProperties(_EventTarget.prototype, { + listeners: { + get: function () { + return this._listeners; + } + } +}); + +function _addEventListener(type, newListener) { + var + listenersType, + i, listener; + + if (!type || !newListener) { + return; + } + + listenersType = this._listeners[type]; + if (listenersType === undefined) { + this._listeners[type] = listenersType = []; + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (listener === newListener) { + return; + } + } + + listenersType.push(newListener); +} + +function _removeEventListener(type, oldListener) { + var + listenersType, + i, listener; + + if (!type || !oldListener) { + return; + } + + listenersType = this._listeners[type]; + if (listenersType === undefined) { + return; + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (listener === oldListener) { + listenersType.splice(i, 1); + break; + } + } + + if (listenersType.length === 0) { + delete this._listeners[type]; + } +} + +function _dispatchEvent(event) { + var + type, + listenersType, + dummyListener, + stopImmediatePropagation = false, + i, listener; + + if (!event || typeof event.type !== 'string') { + throw new Error('`event` must have a valid `type` property'); + } + + // Do some stuff to emulate DOM Event behavior (just if this is not a + // DOM Event object) + if (event._yaeti) { + event.target = this; + event.cancelable = true; + } + + // Attempt to override the stopImmediatePropagation() method + try { + event.stopImmediatePropagation = function () { + stopImmediatePropagation = true; + }; + } catch (error) {} + + type = event.type; + listenersType = (this._listeners[type] || []); + + dummyListener = this['on' + type]; + if (typeof dummyListener === 'function') { + dummyListener.call(this, event); + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (stopImmediatePropagation) { + break; + } + + listener.call(this, event); + } + + return !event.defaultPrevented; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/package.json new file mode 100644 index 0000000000000000000000000000000000000000..abbbda20c0a452c4f4eca2cd09342f16596d281d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/node_modules/yaeti/package.json @@ -0,0 +1,57 @@ +{ + "_from": "yaeti@^0.0.6", + "_id": "yaeti@0.0.6", + "_inBundle": false, + "_integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=", + "_location": "/yaeti", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yaeti@^0.0.6", + "name": "yaeti", + "escapedName": "yaeti", + "rawSpec": "^0.0.6", + "saveSpec": null, + "fetchSpec": "^0.0.6" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "_shasum": "f26f484d72684cf42bedfb76970aa1608fbf9577", + "_spec": "yaeti@^0.0.6", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net" + }, + "browser": { + "./lib/Event.js": "./lib/Event.browser.js" + }, + "bugs": { + "url": "https://github.com/ibc/yaeti/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Yet Another EventTarget Implementation", + "devDependencies": { + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jscs": "^1.6.0", + "gulp-jscs-stylish": "^1.1.0", + "gulp-jshint": "^1.11.2", + "jshint-stylish": "~1.0.2" + }, + "engines": { + "node": ">=0.10.32" + }, + "homepage": "https://github.com/ibc/yaeti#readme", + "license": "MIT", + "main": "index.js", + "name": "yaeti", + "repository": { + "type": "git", + "url": "git+https://github.com/ibc/yaeti.git" + }, + "version": "0.0.6" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/package-lock.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..601d07db72e60296809fc1390c539f0180efef89 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/package-lock.json @@ -0,0 +1,66 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "nan": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==" + }, + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "requires": { + "is-typedarray": "1.0.0" + } + }, + "websocket": { + "version": "1.0.25", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.25.tgz", + "integrity": "sha512-M58njvi6ZxVb5k7kpnHh2BvNKuBWiwIYvsToErBzWhvBZYwlEiLcyLrG41T1jRcrY9ettqPYEqduLI7ul54CVQ==", + "requires": { + "debug": "2.6.9", + "nan": "2.10.0", + "typedarray-to-buffer": "3.1.5", + "yaeti": "0.0.6" + } + }, + "ws": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.0.0.tgz", + "integrity": "sha512-XXG4S0b771C68AeTHebBsJJBZMguxj7Em+D657RViuj6ppRd3tfuOhIK8eGwZGNb76C8MjQfCTfH2NN50rJN4w==", + "requires": { + "async-limiter": "1.0.0" + } + }, + "yaeti": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=" + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/r.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/r.js new file mode 100644 index 0000000000000000000000000000000000000000..d8c8dc4bf59f9463821d7951f1becc27c7c724b4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/r.js @@ -0,0 +1,30419 @@ +/** + * @license r.js 2.3.5 Copyright jQuery Foundation and other contributors. + * Released under MIT license, http://github.com/requirejs/r.js/LICENSE + */ + +/* + * This is a bootstrap script to allow running RequireJS in the command line + * in either a Java/Rhino or Node environment. It is modified by the top-level + * dist.js file to inject other files to completely enable this file. It is + * the shell of the r.js file. + */ + +/*jslint evil: true, nomen: true, sloppy: true */ +/*global readFile: true, process: false, Packages: false, print: false, +console: false, java: false, module: false, requirejsVars, navigator, +document, importScripts, self, location, Components, FileUtils */ + +var requirejs, require, define, xpcUtil; +(function (console, args, readFileFunc) { + var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire, + nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci, + version = '2.3.5', + jsSuffixRegExp = /\.js$/, + commandOption = '', + useLibLoaded = {}, + //Used by jslib/rhino/args.js + rhinoArgs = args, + //Used by jslib/xpconnect/args.js + xpconnectArgs = args, + readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null; + + function showHelp() { + console.log('See https://github.com/requirejs/r.js for usage.'); + } + + if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { + env = 'node'; + + //Get the fs module via Node's require before it + //gets replaced. Used in require/node.js + fs = require('fs'); + vm = require('vm'); + path = require('path'); + //In Node 0.7+ existsSync is on fs. + existsForNode = fs.existsSync || path.existsSync; + + nodeRequire = require; + nodeDefine = define; + reqMain = require.main; + + //Temporarily hide require and define to allow require.js to define + //them. + require = undefined; + define = undefined; + + readFile = function (path) { + return fs.readFileSync(path, 'utf8'); + }; + + exec = function (string, name) { + return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string), + name ? fs.realpathSync(name) : ''); + }; + + exists = function (fileName) { + return existsForNode(fileName); + }; + + + fileName = process.argv[2]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = process.argv[3]; + } + } else if (typeof Packages !== 'undefined') { + env = 'rhino'; + + fileName = args[0]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = args[1]; + } + + //Exec/readFile differs between Rhino and Nashorn. Rhino has an + //importPackage where Nashorn does not, so branch on that. This is a + //coarser check -- detecting readFile existence might also be enough for + //this spot. However, sticking with importPackage to keep it the same + //as other Rhino/Nashorn detection branches. + if (typeof importPackage !== 'undefined') { + rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext(); + + exec = function (string, name) { + return rhinoContext.evaluateString(this, string, name, 0, null); + }; + } else { + exec = function (string, name) { + load({ script: string, name: name}); + }; + readFile = readFully; + } + + exists = function (fileName) { + return (new java.io.File(fileName)).exists(); + }; + + //Define a console.log for easier logging. Don't + //get fancy though. + if (typeof console === 'undefined') { + console = { + log: function () { + print.apply(undefined, arguments); + } + }; + } + } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || + (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { + env = 'browser'; + + readFile = function (path) { + return fs.readFileSync(path, 'utf8'); + }; + + exec = function (string) { + return eval(string); + }; + + exists = function () { + console.log('x.js exists not applicable in browser env'); + return false; + }; + + } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { + env = 'xpconnect'; + + Components.utils['import']('resource://gre/modules/FileUtils.jsm'); + Cc = Components.classes; + Ci = Components.interfaces; + + fileName = args[0]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = args[1]; + } + + xpcUtil = { + isWindows: ('@mozilla.org/windows-registry-key;1' in Cc), + cwd: function () { + return FileUtils.getFile("CurWorkD", []).path; + }, + + //Remove . and .. from paths, normalize on front slashes + normalize: function (path) { + //There has to be an easier way to do this. + var i, part, ary, + firstChar = path.charAt(0); + + if (firstChar !== '/' && + firstChar !== '\\' && + path.indexOf(':') === -1) { + //A relative path. Use the current working directory. + path = xpcUtil.cwd() + '/' + path; + } + + ary = path.replace(/\\/g, '/').split('/'); + + for (i = 0; i < ary.length; i += 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + ary.splice(i - 1, 2); + i -= 2; + } + } + return ary.join('/'); + }, + + xpfile: function (path) { + var fullPath; + try { + fullPath = xpcUtil.normalize(path); + if (xpcUtil.isWindows) { + fullPath = fullPath.replace(/\//g, '\\'); + } + return new FileUtils.File(fullPath); + } catch (e) { + throw new Error((fullPath || path) + ' failed: ' + e); + } + }, + + readFile: function (/*String*/path, /*String?*/encoding) { + //A file read function that can deal with BOMs + encoding = encoding || "utf-8"; + + var inStream, convertStream, + readData = {}, + fileObj = xpcUtil.xpfile(path); + + //XPCOM, you so crazy + try { + inStream = Cc['@mozilla.org/network/file-input-stream;1'] + .createInstance(Ci.nsIFileInputStream); + inStream.init(fileObj, 1, 0, false); + + convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] + .createInstance(Ci.nsIConverterInputStream); + convertStream.init(inStream, encoding, inStream.available(), + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + + convertStream.readString(inStream.available(), readData); + return readData.value; + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } finally { + if (convertStream) { + convertStream.close(); + } + if (inStream) { + inStream.close(); + } + } + } + }; + + readFile = xpcUtil.readFile; + + exec = function (string) { + return eval(string); + }; + + exists = function (fileName) { + return xpcUtil.xpfile(fileName).exists(); + }; + + //Define a console.log for easier logging. Don't + //get fancy though. + if (typeof console === 'undefined') { + console = { + log: function () { + print.apply(undefined, arguments); + } + }; + } + } + + /** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.3.5 Copyright jQuery Foundation and other contributors. + * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE + */ +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + + +(function (global, setTimeout) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.3.5', + commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), + isWebWorker = !isBrowser && typeof importScripts !== 'undefined', + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + //Could match something like ')//comment', do not lose the prefix to comment. + function commentReplace(match, singlePrefix) { + return singlePrefix || ''; + } + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (isNormalized) { + normalizedName = name; + } else if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + var resLoadMaps = []; + each(this.depMaps, function (depMap) { + resLoadMaps.push(depMap.normalizedMap || depMap); + }); + req.onResourceLoad(context, this.map, resLoadMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap, + true); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.map.normalizedMap = normalizedMap; + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Allow plugins to load other code without having to know the + //context or how to 'complete' the load. + load.fromText = bind(this, function (text, textAlt) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + context.defQueueMap = {}; + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + defQueueMap: {}, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + // Convert old style urlArgs string to a function. + if (typeof cfg.urlArgs === 'string') { + var urlArgs = cfg.urlArgs; + cfg.urlArgs = function(id, url) { + return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; + }; + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id, null, true); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + mod.undefed = true; + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + context.defQueueMap = {}; + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs && !/^blob\:/.test(url) ? + url + config.urlArgs(moduleName, url) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + onScriptLoad: function (evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + var parents = []; + eachProp(registry, function(value, key) { + if (key.indexOf('_@r') !== 0) { + each(value.depMaps, function(depMap) { + if (depMap.id === data.id) { + parents.push(key); + return true; + } + }); + } + }); + return onError(makeError('scripterror', 'Script error for "' + data.id + + (parents.length ? + '", needed by: ' + parents.join(', ') : + '"'), evt, [data.id])); + } + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if (node.attachEvent && + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/requirejs/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/requirejs/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. + useInteractive = true; + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); + } + node.src = url; + + //Calling onNodeCreated after all properties on the node have been + //set, but before it is placed in the DOM. + if (config.onNodeCreated) { + config.onNodeCreated(node, config, moduleName, url); + } + + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if (baseElement) { + head.insertBefore(node, baseElement); + } else { + head.appendChild(node); + } + currentlyAddingScript = null; + + return node; + } else if (isWebWorker) { + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation is that a build has been done so + //that only one script needs to be loaded anyway. This may need + //to be reevaluated if other use cases become common. + + // Post a task to the event loop to work around a bug in WebKit + // where the worker gets garbage-collected after calling + // importScripts(): https://webkit.org/b/153317 + setTimeout(function() {}, 0); + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by + //using the script's parent. + if (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one, + //but only do so if the data-main value is not a loader plugin + //module ID. + if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + } + + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; + } + }); + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, commentReplace) + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } + }; + + define.amd = { + jQuery: true + }; + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout))); + + + + this.requirejsVars = { + require: require, + requirejs: require, + define: define + }; + + if (env === 'browser') { + //sloppy since eval enclosed with use strict causes problems if the source +//text is not strict-compliant. +/*jslint sloppy: true, evil: true */ +/*global require, XMLHttpRequest */ + +(function () { + // Separate function to avoid eval pollution, same with arguments use. + function exec() { + eval(arguments[0]); + } + + require.load = function (context, moduleName, url) { + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url, true); + xhr.send(); + + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + exec(xhr.responseText); + + //Support anonymous modules. + context.completeLoad(moduleName); + } + }; + }; +}()); + } else if (env === 'rhino') { + /*global require: false, java: false, load: false */ + +(function () { + 'use strict'; + require.load = function (context, moduleName, url) { + + load(url); + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + +}()); + } else if (env === 'node') { + this.requirejsVars.nodeRequire = nodeRequire; + require.nodeRequire = nodeRequire; + + //Explicity not strict since this file contains an eval call, and do not want +//to enforce strict on code evaluated that way. See +//https://github.com/requirejs/r.js/issues/774 +/*jslint regexp: false, sloppy: true*/ +/*global require: false, define: false, requirejsVars: false, process: false */ + +/** + * This adapter assumes that x.js has loaded it and set up + * some variables. This adapter just allows limited RequireJS + * usage from within the requirejs directory. The general + * node adapater is r.js. + */ + +(function () { + var nodeReq = requirejsVars.nodeRequire, + req = requirejsVars.require, + def = requirejsVars.define, + fs = nodeReq('fs'), + path = nodeReq('path'), + vm = nodeReq('vm'), + //In Node 0.7+ existsSync is on fs. + exists = fs.existsSync || path.existsSync, + hasOwn = Object.prototype.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function syncTick(fn) { + fn(); + } + + function makeError(message, moduleName) { + var err = new Error(message); + err.requireModules = [moduleName]; + return err; + } + + //Supply an implementation that allows synchronous get of a module. + req.get = function (context, moduleName, relModuleMap, localRequire) { + if (moduleName === "require" || moduleName === "exports" || moduleName === "module") { + context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName)); + } + + var ret, oldTick, + moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true); + + //Normalize module name, if it contains . or .. + moduleName = moduleMap.id; + + if (hasProp(context.defined, moduleName)) { + ret = context.defined[moduleName]; + } else { + if (ret === undefined) { + //Make sure nextTick for this type of call is sync-based. + oldTick = context.nextTick; + context.nextTick = syncTick; + try { + if (moduleMap.prefix) { + //A plugin, call requirejs to handle it. Now that + //nextTick is syncTick, the require will complete + //synchronously. + localRequire([moduleMap.originalName]); + + //Now that plugin is loaded, can regenerate the moduleMap + //to get the final, normalized ID. + moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true); + moduleName = moduleMap.id; + } else { + //Try to dynamically fetch it. + req.load(context, moduleName, moduleMap.url); + + //Enable the module + context.enable(moduleMap, relModuleMap); + } + + //Break any cycles by requiring it normally, but this will + //finish synchronously + context.require([moduleName]); + + //The above calls are sync, so can do the next thing safely. + ret = context.defined[moduleName]; + } finally { + context.nextTick = oldTick; + } + } + } + + return ret; + }; + + req.nextTick = function (fn) { + process.nextTick(fn); + }; + + //Add wrapper around the code so that it gets the requirejs + //API instead of the Node API, and it is done lexically so + //that it survives later execution. + req.makeNodeWrapper = function (contents) { + return '(function (require, requirejs, define) { ' + + contents + + '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));'; + }; + + req.load = function (context, moduleName, url) { + var contents, err, + config = context.config; + + if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) { + console.warn('Shim config not supported in Node, may or may not work. Detected ' + + 'for module: ' + moduleName); + } + + if (exists(url)) { + contents = fs.readFileSync(url, 'utf8'); + + contents = req.makeNodeWrapper(contents); + try { + vm.runInThisContext(contents, fs.realpathSync(url)); + } catch (e) { + err = new Error('Evaluating ' + url + ' as module "' + + moduleName + '" failed with error: ' + e); + err.originalError = e; + err.moduleName = moduleName; + err.requireModules = [moduleName]; + err.fileName = url; + return context.onError(err); + } + } else { + def(moduleName, function () { + //Get the original name, since relative requires may be + //resolved differently in node (issue #202). Also, if relative, + //make it relative to the URL of the item requesting it + //(issue #393) + var dirName, + map = hasProp(context.registry, moduleName) && + context.registry[moduleName].map, + parentMap = map && map.parentMap, + originalName = map && map.originalName; + + if (originalName.charAt(0) === '.' && parentMap) { + dirName = parentMap.url.split('/'); + dirName.pop(); + originalName = dirName.join('/') + '/' + originalName; + } + + try { + return (context.config.nodeRequire || req.nodeRequire)(originalName); + } catch (e) { + err = new Error('Tried loading "' + moduleName + '" at ' + + url + ' then tried node\'s require("' + + originalName + '") and it failed ' + + 'with error: ' + e); + err.originalError = e; + err.moduleName = originalName; + err.requireModules = [moduleName]; + throw err; + } + }); + } + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + + //Override to provide the function wrapper for define/require. + req.exec = function (text) { + /*jslint evil: true */ + text = req.makeNodeWrapper(text); + return eval(text); + }; +}()); + + } else if (env === 'xpconnect') { + /*jslint */ +/*global require, load */ + +(function () { + 'use strict'; + require.load = function (context, moduleName, url) { + + load(url); + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + +}()); + + } + + //Support a default file name to execute. Useful for hosted envs + //like Joyent where it defaults to a server.js as the only executed + //script. But only do it if this is not an optimization run. + if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) { + fileName = 'main.js'; + } + + /** + * Loads the library files that can be used for the optimizer, or for other + * tasks. + */ + function loadLib() { + /*jslint strict: false */ +/*global Packages: false, process: false, window: false, navigator: false, + document: false, define: false */ + +/** + * A plugin that modifies any /env/ path to be the right path based on + * the host environment. Right now only works for Node, Rhino and browser. + */ +(function () { + var pathRegExp = /(\/|^)env\/|\{env\}/, + env = 'unknown'; + + if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { + env = 'node'; + } else if (typeof Packages !== 'undefined') { + env = 'rhino'; + } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || + (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { + env = 'browser'; + } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { + env = 'xpconnect'; + } + + define('env', { + get: function () { + return env; + }, + + load: function (name, req, load, config) { + //Allow override in the config. + if (config.env) { + env = config.env; + } + + name = name.replace(pathRegExp, function (match, prefix) { + if (match.indexOf('{') === -1) { + return prefix + env + '/'; + } else { + return env; + } + }); + + req([name], function (mod) { + load(mod); + }); + } + }); +}()); +/*jslint plusplus: true */ +/*global define, java */ + +define('lang', function () { + 'use strict'; + + var lang, isJavaObj, + hasOwn = Object.prototype.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + isJavaObj = function () { + return false; + }; + + //Rhino, but not Nashorn (detected by importPackage not existing) + //Can have some strange foreign objects. + if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') { + isJavaObj = function (obj) { + return obj instanceof java.lang.Object; + }; + } + + lang = { + backSlashRegExp: /\\/g, + ostring: Object.prototype.toString, + + isArray: Array.isArray || function (it) { + return lang.ostring.call(it) === "[object Array]"; + }, + + isFunction: function(it) { + return lang.ostring.call(it) === "[object Function]"; + }, + + isRegExp: function(it) { + return it && it instanceof RegExp; + }, + + hasProp: hasProp, + + //returns true if the object does not have an own property prop, + //or if it does, it is a falsy value. + falseProp: function (obj, prop) { + return !hasProp(obj, prop) || !obj[prop]; + }, + + //gets own property value for given prop on object + getOwn: function (obj, prop) { + return hasProp(obj, prop) && obj[prop]; + }, + + _mixin: function(dest, source, override){ + var name; + for (name in source) { + if(source.hasOwnProperty(name) && + (override || !dest.hasOwnProperty(name))) { + dest[name] = source[name]; + } + } + + return dest; // Object + }, + + /** + * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean, + * then the source objects properties are force copied over to dest. + */ + mixin: function(dest){ + var parameters = Array.prototype.slice.call(arguments), + override, i, l; + + if (!dest) { dest = {}; } + + if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') { + override = parameters.pop(); + } + + for (i = 1, l = parameters.length; i < l; i++) { + lang._mixin(dest, parameters[i], override); + } + return dest; // Object + }, + + /** + * Does a deep mix of source into dest, where source values override + * dest values if a winner is needed. + * @param {Object} dest destination object that receives the mixed + * values. + * @param {Object} source source object contributing properties to mix + * in. + * @return {[Object]} returns dest object with the modification. + */ + deepMix: function(dest, source) { + lang.eachProp(source, function (value, prop) { + if (typeof value === 'object' && value && + !lang.isArray(value) && !lang.isFunction(value) && + !(value instanceof RegExp)) { + + if (!dest[prop]) { + dest[prop] = {}; + } + lang.deepMix(dest[prop], value); + } else { + dest[prop] = value; + } + }); + return dest; + }, + + /** + * Does a type of deep copy. Do not give it anything fancy, best + * for basic object copies of objects that also work well as + * JSON-serialized things, or has properties pointing to functions. + * For non-array/object values, just returns the same object. + * @param {Object} obj copy properties from this object + * @param {Object} [ignoredProps] optional object whose own properties + * are keys that should be ignored. + * @return {Object} + */ + deeplikeCopy: function (obj, ignoredProps) { + var type, result; + + if (lang.isArray(obj)) { + result = []; + obj.forEach(function(value) { + result.push(lang.deeplikeCopy(value, ignoredProps)); + }); + return result; + } + + type = typeof obj; + if (obj === null || obj === undefined || type === 'boolean' || + type === 'string' || type === 'number' || lang.isFunction(obj) || + lang.isRegExp(obj)|| isJavaObj(obj)) { + return obj; + } + + //Anything else is an object, hopefully. + result = {}; + lang.eachProp(obj, function(value, key) { + if (!ignoredProps || !hasProp(ignoredProps, key)) { + result[key] = lang.deeplikeCopy(value, ignoredProps); + } + }); + return result; + }, + + delegate: (function () { + // boodman/crockford delegation w/ cornford optimization + function TMP() {} + return function (obj, props) { + TMP.prototype = obj; + var tmp = new TMP(); + TMP.prototype = null; + if (props) { + lang.mixin(tmp, props); + } + return tmp; // Object + }; + }()), + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + each: function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (func(ary[i], i, ary)) { + break; + } + } + } + }, + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + eachProp: function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + }, + + //Similar to Function.prototype.bind, but the "this" object is specified + //first, since it is easier to read/figure out what "this" will be. + bind: function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + }, + + //Escapes a content string to be be a string that has characters escaped + //for inclusion as part of a JS string. + jsEscape: function (content) { + return content.replace(/(["'\\])/g, '\\$1') + .replace(/[\f]/g, "\\f") + .replace(/[\b]/g, "\\b") + .replace(/[\n]/g, "\\n") + .replace(/[\t]/g, "\\t") + .replace(/[\r]/g, "\\r"); + } + }; + return lang; +}); +/** + * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/requirejs/prim for details + */ + +/*global setImmediate, process, setTimeout, define, module */ + +//Set prime.hideResolutionConflict = true to allow "resolution-races" +//in promise-tests to pass. +//Since the goal of prim is to be a small impl for trusted code, it is +//more important to normally throw in this case so that we can find +//logic errors quicker. + +var prim; +(function () { + 'use strict'; + var op = Object.prototype, + hasOwn = op.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i]) { + func(ary[i], i, ary); + } + } + } + } + + function check(p) { + if (hasProp(p, 'e') || hasProp(p, 'v')) { + if (!prim.hideResolutionConflict) { + throw new Error('Prim promise already resolved: ' + + JSON.stringify(p)); + } + return false; + } + return true; + } + + function notify(ary, value) { + prim.nextTick(function () { + each(ary, function (item) { + item(value); + }); + }); + } + + prim = function prim() { + var p, + ok = [], + fail = []; + + return (p = { + callback: function (yes, no) { + if (no) { + p.errback(no); + } + + if (hasProp(p, 'v')) { + prim.nextTick(function () { + yes(p.v); + }); + } else { + ok.push(yes); + } + }, + + errback: function (no) { + if (hasProp(p, 'e')) { + prim.nextTick(function () { + no(p.e); + }); + } else { + fail.push(no); + } + }, + + finished: function () { + return hasProp(p, 'e') || hasProp(p, 'v'); + }, + + rejected: function () { + return hasProp(p, 'e'); + }, + + resolve: function (v) { + if (check(p)) { + p.v = v; + notify(ok, v); + } + return p; + }, + reject: function (e) { + if (check(p)) { + p.e = e; + notify(fail, e); + } + return p; + }, + + start: function (fn) { + p.resolve(); + return p.promise.then(fn); + }, + + promise: { + then: function (yes, no) { + var next = prim(); + + p.callback(function (v) { + try { + if (yes && typeof yes === 'function') { + v = yes(v); + } + + if (v && v.then) { + v.then(next.resolve, next.reject); + } else { + next.resolve(v); + } + } catch (e) { + next.reject(e); + } + }, function (e) { + var err; + + try { + if (!no || typeof no !== 'function') { + next.reject(e); + } else { + err = no(e); + + if (err && err.then) { + err.then(next.resolve, next.reject); + } else { + next.resolve(err); + } + } + } catch (e2) { + next.reject(e2); + } + }); + + return next.promise; + }, + + fail: function (no) { + return p.promise.then(null, no); + }, + + end: function () { + p.errback(function (e) { + throw e; + }); + } + } + }); + }; + + prim.serial = function (ary) { + var result = prim().resolve().promise; + each(ary, function (item) { + result = result.then(function () { + return item(); + }); + }); + return result; + }; + + prim.nextTick = typeof setImmediate === 'function' ? setImmediate : + (typeof process !== 'undefined' && process.nextTick ? + process.nextTick : (typeof setTimeout !== 'undefined' ? + function (fn) { + setTimeout(fn, 0); + } : function (fn) { + fn(); + })); + + if (typeof define === 'function' && define.amd) { + define('prim', function () { return prim; }); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = prim; + } +}()); +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('browser/assert', function () { + return {}; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Needed so that rhino/assert can return a stub for uglify's consolidator.js +define('node/assert', ['assert'], function (assert) { + return assert; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('rhino/assert', function () { + return {}; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('xpconnect/assert', function () { + return {}; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, process: false */ + +define('browser/args', function () { + //Always expect config via an API call + return []; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, process: false */ + +define('node/args', function () { + //Do not return the "node" or "r.js" arguments + var args = process.argv.slice(2); + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, process: false */ + +var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); + +define('rhino/args', function () { + var args = jsLibRhinoArgs; + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define, xpconnectArgs */ + +var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); + +define('xpconnect/args', function () { + var args = jsLibXpConnectArgs; + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('browser/load', ['./file'], function (file) { + function load(fileName) { + eval(file.readFile(fileName)); + } + + return load; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('node/load', ['fs'], function (fs) { + function load(fileName) { + var contents = fs.readFileSync(fileName, 'utf8'); + process.compile(contents, fileName); + } + + return load; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, load: false */ + +define('rhino/load', function () { + return load; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, load: false */ + +define('xpconnect/load', function () { + return load; +}); + +} + +if(env === 'browser') { +/*jslint sloppy: true, nomen: true */ +/*global require, define, console, XMLHttpRequest, requirejs, location */ + +define('browser/file', ['prim'], function (prim) { + + var file, + currDirRegExp = /^\.(\/|$)/; + + function frontSlash(path) { + return path.replace(/\\/g, '/'); + } + + function exists(path) { + var status, xhr = new XMLHttpRequest(); + + //Oh yeah, that is right SYNC IO. Behold its glory + //and horrible blocking behavior. + xhr.open('HEAD', path, false); + xhr.send(); + status = xhr.status; + + return status === 200 || status === 304; + } + + function mkDir(dir) { + console.log('mkDir is no-op in browser'); + } + + function mkFullDir(dir) { + console.log('mkFullDir is no-op in browser'); + } + + file = { + backSlashRegExp: /\\/g, + exclusionRegExp: /^\./, + getLineSeparator: function () { + return '/'; + }, + + exists: function (fileName) { + return exists(fileName); + }, + + parent: function (fileName) { + var parts = fileName.split('/'); + parts.pop(); + return parts.join('/'); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {String} fileName + */ + absPath: function (fileName) { + var dir; + if (currDirRegExp.test(fileName)) { + dir = frontSlash(location.href); + if (dir.indexOf('/') !== -1) { + dir = dir.split('/'); + + //Pull off protocol and host, just want + //to allow paths (other build parts, like + //require._isSupportedBuildUrl do not support + //full URLs), but a full path from + //the root. + dir.splice(0, 3); + + dir.pop(); + dir = '/' + dir.join('/'); + } + + fileName = dir + fileName.substring(1); + } + + return fileName; + }, + + normalize: function (fileName) { + return fileName; + }, + + isFile: function (path) { + return true; + }, + + isDirectory: function (path) { + return false; + }, + + getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) { + console.log('file.getFilteredFileList is no-op in browser'); + }, + + copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) { + console.log('file.copyDir is no-op in browser'); + + }, + + copyFile: function (srcFileName, destFileName, onlyCopyNew) { + console.log('file.copyFile is no-op in browser'); + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + console.log('file.renameFile is no-op in browser'); + }, + + /** + * Reads a *text* file. + */ + readFile: function (path, encoding) { + var xhr = new XMLHttpRequest(); + + //Oh yeah, that is right SYNC IO. Behold its glory + //and horrible blocking behavior. + xhr.open('GET', path, false); + xhr.send(); + + return xhr.responseText; + }, + + readFileAsync: function (path, encoding) { + var xhr = new XMLHttpRequest(), + d = prim(); + + xhr.open('GET', path, true); + xhr.send(); + + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + if (xhr.status > 400) { + d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText)); + } else { + d.resolve(xhr.responseText); + } + } + }; + + return d.promise; + }, + + saveUtf8File: function (fileName, fileContents) { + //summary: saves a *text* file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf8"); + }, + + saveFile: function (fileName, fileContents, encoding) { + requirejs.browser.saveFile(fileName, fileContents, encoding); + }, + + deleteFile: function (fileName) { + console.log('file.deleteFile is no-op in browser'); + }, + + /** + * Deletes any empty directories under the given directory. + */ + deleteEmptyDirs: function (startDir) { + console.log('file.deleteEmptyDirs is no-op in browser'); + } + }; + + return file; + +}); + +} + +if(env === 'node') { +/*jslint plusplus: false, octal:false, strict: false */ +/*global define: false, process: false */ + +define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) { + + var isWindows = process.platform === 'win32', + windowsDriveRegExp = /^[a-zA-Z]\:\/$/, + file; + + function frontSlash(path) { + return path.replace(/\\/g, '/'); + } + + function exists(path) { + if (isWindows && path.charAt(path.length - 1) === '/' && + path.charAt(path.length - 2) !== ':') { + path = path.substring(0, path.length - 1); + } + + try { + fs.statSync(path); + return true; + } catch (e) { + return false; + } + } + + function mkDir(dir) { + if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) { + fs.mkdirSync(dir, 511); + } + } + + function mkFullDir(dir) { + var parts = dir.split('/'), + currDir = '', + first = true; + + parts.forEach(function (part) { + //First part may be empty string if path starts with a slash. + currDir += part + '/'; + first = false; + + if (part) { + mkDir(currDir); + } + }); + } + + file = { + backSlashRegExp: /\\/g, + exclusionRegExp: /^\./, + getLineSeparator: function () { + return '/'; + }, + + exists: function (fileName) { + return exists(fileName); + }, + + parent: function (fileName) { + var parts = fileName.split('/'); + parts.pop(); + return parts.join('/'); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {String} fileName + */ + absPath: function (fileName) { + return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName)))); + }, + + normalize: function (fileName) { + return frontSlash(path.normalize(fileName)); + }, + + isFile: function (path) { + return fs.statSync(path).isFile(); + }, + + isDirectory: function (path) { + return fs.statSync(path).isDirectory(); + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + i, stat, filePath, ok, dirFiles, fileName; + + topDir = startDir; + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (file.exists(topDir)) { + dirFileArray = fs.readdirSync(topDir); + for (i = 0; i < dirFileArray.length; i++) { + fileName = dirFileArray[i]; + filePath = path.join(topDir, fileName); + stat = fs.statSync(filePath); + if (stat.isFile()) { + if (makeUnixPaths) { + //Make sure we have a JS string. + if (filePath.indexOf("/") === -1) { + filePath = frontSlash(filePath); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileName))) { + files.push(filePath); + } + } else if (stat.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) { + dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + //Normalize th directory names, but keep front slashes. + //path module on windows now returns backslashed paths. + srcDir = frontSlash(path.normalize(srcDir)); + destDir = frontSlash(path.normalize(destDir)); + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i++) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var parentDir; + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) { + return false; //Boolean + } + } + + //Make sure destination dir exists. + parentDir = path.dirname(destFileName); + if (!file.exists(parentDir)) { + mkFullDir(parentDir); + } + + fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary'); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + return fs.renameSync(from, to); + }, + + /** + * Reads a *text* file. + */ + readFile: function (/*String*/path, /*String?*/encoding) { + if (encoding === 'utf-8') { + encoding = 'utf8'; + } + if (!encoding) { + encoding = 'utf8'; + } + + var text = fs.readFileSync(path, encoding); + + //Hmm, would not expect to get A BOM, but it seems to happen, + //remove it just in case. + if (text.indexOf('\uFEFF') === 0) { + text = text.substring(1, text.length); + } + + return text; + }, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a *text* file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + //summary: saves a *text* file. + var parentDir; + + if (encoding === 'utf-8') { + encoding = 'utf8'; + } + if (!encoding) { + encoding = 'utf8'; + } + + //Make sure destination directories exist. + parentDir = path.dirname(fileName); + if (!file.exists(parentDir)) { + mkFullDir(parentDir); + } + + fs.writeFileSync(fileName, fileContents, encoding); + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var files, i, stat; + if (file.exists(fileName)) { + stat = fs.lstatSync(fileName); + if (stat.isDirectory()) { + files = fs.readdirSync(fileName); + for (i = 0; i < files.length; i++) { + this.deleteFile(path.join(fileName, files[i])); + } + fs.rmdirSync(fileName); + } else { + fs.unlinkSync(fileName); + } + } + }, + + + /** + * Deletes any empty directories under the given directory. + */ + deleteEmptyDirs: function (startDir) { + var dirFileArray, i, fileName, filePath, stat; + + if (file.exists(startDir)) { + dirFileArray = fs.readdirSync(startDir); + for (i = 0; i < dirFileArray.length; i++) { + fileName = dirFileArray[i]; + filePath = path.join(startDir, fileName); + stat = fs.lstatSync(filePath); + if (stat.isDirectory()) { + file.deleteEmptyDirs(filePath); + } + } + + //If directory is now empty, remove it. + if (fs.readdirSync(startDir).length === 0) { + file.deleteFile(startDir); + } + } + } + }; + + return file; + +}); + +} + +if(env === 'rhino') { +//Helper functions to deal with file I/O. + +/*jslint plusplus: false */ +/*global java: false, define: false */ + +define('rhino/file', ['prim'], function (prim) { + var file = { + backSlashRegExp: /\\/g, + + exclusionRegExp: /^\./, + + getLineSeparator: function () { + return file.lineSeparator; + }, + + lineSeparator: java.lang.System.getProperty("line.separator"), //Java String + + exists: function (fileName) { + return (new java.io.File(fileName)).exists(); + }, + + parent: function (fileName) { + return file.absPath((new java.io.File(fileName)).getParentFile()); + }, + + normalize: function (fileName) { + return file.absPath(fileName); + }, + + isFile: function (path) { + return (new java.io.File(path)).isFile(); + }, + + isDirectory: function (path) { + return (new java.io.File(path)).isDirectory(); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {java.io.File||String} file + */ + absPath: function (fileObj) { + if (typeof fileObj === "string") { + fileObj = new java.io.File(fileObj); + } + return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/"); + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + i, fileObj, filePath, ok, dirFiles; + + topDir = startDir; + if (!startDirIsJavaObject) { + topDir = new java.io.File(startDir); + } + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (topDir.exists()) { + dirFileArray = topDir.listFiles(); + for (i = 0; i < dirFileArray.length; i++) { + fileObj = dirFileArray[i]; + if (fileObj.isFile()) { + filePath = fileObj.getPath(); + if (makeUnixPaths) { + //Make sure we have a JS string. + filePath = String(filePath); + if (filePath.indexOf("/") === -1) { + filePath = filePath.replace(/\\/g, "/"); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileObj.getName()))) { + files.push(filePath); + } + } else if (fileObj.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) { + dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i++) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var destFile = new java.io.File(destFileName), srcFile, parentDir, + srcChannel, destChannel; + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + srcFile = new java.io.File(srcFileName); + if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) { + return false; //Boolean + } + } + + //Make sure destination dir exists. + parentDir = destFile.getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getCanonicalPath(); + } + } + + //Java's version of copy file. + srcChannel = new java.io.FileInputStream(srcFileName).getChannel(); + destChannel = new java.io.FileOutputStream(destFileName).getChannel(); + destChannel.transferFrom(srcChannel, 0, srcChannel.size()); + srcChannel.close(); + destChannel.close(); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + return (new java.io.File(from)).renameTo((new java.io.File(to))); + }, + + readFile: function (/*String*/path, /*String?*/encoding) { + //A file read function that can deal with BOMs + encoding = encoding || "utf-8"; + var fileObj = new java.io.File(path), + input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)), + stringBuffer, line; + try { + stringBuffer = new java.lang.StringBuffer(); + line = input.readLine(); + + // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 + // http://www.unicode.org/faq/utf_bom.html + + // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 + if (line && line.length() && line.charAt(0) === 0xfeff) { + // Eat the BOM, since we've already found the encoding on this file, + // and we plan to concatenating this buffer with others; the BOM should + // only appear at the top of a file. + line = line.substring(1); + } + while (line !== null) { + stringBuffer.append(line); + stringBuffer.append(file.lineSeparator); + line = input.readLine(); + } + //Make sure we return a JavaScript string and not a Java string. + return String(stringBuffer.toString()); //String + } finally { + input.close(); + } + }, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf-8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + //summary: saves a file. + var outFile = new java.io.File(fileName), outWriter, parentDir, os; + + parentDir = outFile.getAbsoluteFile().getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getAbsolutePath(); + } + } + + if (encoding) { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); + } else { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); + } + + os = new java.io.BufferedWriter(outWriter); + try { + //If in Nashorn, need to coerce the JS string to a Java string so that + //writer.write method dispatch correctly detects the type. + if (typeof importPackage !== 'undefined') { + os.write(fileContents); + } else { + os.write(new java.lang.String(fileContents)); + } + } finally { + os.close(); + } + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var fileObj = new java.io.File(fileName), files, i; + if (fileObj.exists()) { + if (fileObj.isDirectory()) { + files = fileObj.listFiles(); + for (i = 0; i < files.length; i++) { + this.deleteFile(files[i]); + } + } + fileObj["delete"](); + } + }, + + /** + * Deletes any empty directories under the given directory. + * The startDirIsJavaObject is private to this implementation's + * recursion needs. + */ + deleteEmptyDirs: function (startDir, startDirIsJavaObject) { + var topDir = startDir, + dirFileArray, i, fileObj; + + if (!startDirIsJavaObject) { + topDir = new java.io.File(startDir); + } + + if (topDir.exists()) { + dirFileArray = topDir.listFiles(); + for (i = 0; i < dirFileArray.length; i++) { + fileObj = dirFileArray[i]; + if (fileObj.isDirectory()) { + file.deleteEmptyDirs(fileObj, true); + } + } + + //If the directory is empty now, delete it. + if (topDir.listFiles().length === 0) { + file.deleteFile(String(topDir.getPath())); + } + } + } + }; + + return file; +}); + +} + +if(env === 'xpconnect') { +//Helper functions to deal with file I/O. + +/*jslint plusplus: false */ +/*global define, Components, xpcUtil */ + +define('xpconnect/file', ['prim'], function (prim) { + var file, + Cc = Components.classes, + Ci = Components.interfaces, + //Depends on xpcUtil which is set up in x.js + xpfile = xpcUtil.xpfile; + + function mkFullDir(dirObj) { + //1 is DIRECTORY_TYPE, 511 is 0777 permissions + if (!dirObj.exists()) { + dirObj.create(1, 511); + } + } + + file = { + backSlashRegExp: /\\/g, + + exclusionRegExp: /^\./, + + getLineSeparator: function () { + return file.lineSeparator; + }, + + lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ? + '\r\n' : '\n', + + exists: function (fileName) { + return xpfile(fileName).exists(); + }, + + parent: function (fileName) { + return xpfile(fileName).parent; + }, + + normalize: function (fileName) { + return file.absPath(fileName); + }, + + isFile: function (path) { + return xpfile(path).isFile(); + }, + + isDirectory: function (path) { + return xpfile(path).isDirectory(); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {java.io.File||String} file + */ + absPath: function (fileObj) { + if (typeof fileObj === "string") { + fileObj = xpfile(fileObj); + } + return fileObj.path; + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + fileObj, filePath, ok, dirFiles; + + topDir = startDir; + if (!startDirIsObject) { + topDir = xpfile(startDir); + } + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (topDir.exists()) { + dirFileArray = topDir.directoryEntries; + while (dirFileArray.hasMoreElements()) { + fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); + if (fileObj.isFile()) { + filePath = fileObj.path; + if (makeUnixPaths) { + if (filePath.indexOf("/") === -1) { + filePath = filePath.replace(/\\/g, "/"); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileObj.leafName))) { + files.push(filePath); + } + } else if (fileObj.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) { + dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i += 1) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var destFile = xpfile(destFileName), + srcFile = xpfile(srcFileName); + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) { + return false; //Boolean + } + } + + srcFile.copyTo(destFile.parent, destFile.leafName); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + var toFile = xpfile(to); + return xpfile(from).moveTo(toFile.parent, toFile.leafName); + }, + + readFile: xpcUtil.readFile, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf-8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + var outStream, convertStream, + fileObj = xpfile(fileName); + + mkFullDir(fileObj.parent); + + try { + outStream = Cc['@mozilla.org/network/file-output-stream;1'] + .createInstance(Ci.nsIFileOutputStream); + //438 is decimal for 0777 + outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0); + + convertStream = Cc['@mozilla.org/intl/converter-output-stream;1'] + .createInstance(Ci.nsIConverterOutputStream); + + convertStream.init(outStream, encoding, 0, 0); + convertStream.writeString(fileContents); + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } finally { + if (convertStream) { + convertStream.close(); + } + if (outStream) { + outStream.close(); + } + } + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var fileObj = xpfile(fileName); + if (fileObj.exists()) { + fileObj.remove(true); + } + }, + + /** + * Deletes any empty directories under the given directory. + * The startDirIsJavaObject is private to this implementation's + * recursion needs. + */ + deleteEmptyDirs: function (startDir, startDirIsObject) { + var topDir = startDir, + dirFileArray, fileObj; + + if (!startDirIsObject) { + topDir = xpfile(startDir); + } + + if (topDir.exists()) { + dirFileArray = topDir.directoryEntries; + while (dirFileArray.hasMoreElements()) { + fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); + + if (fileObj.isDirectory()) { + file.deleteEmptyDirs(fileObj, true); + } + } + + //If the directory is empty now, delete it. + dirFileArray = topDir.directoryEntries; + if (!dirFileArray.hasMoreElements()) { + file.deleteFile(topDir.path); + } + } + } + }; + + return file; +}); + +} + +if(env === 'browser') { +/*global process */ +define('browser/quit', function () { + 'use strict'; + return function (code) { + }; +}); +} + +if(env === 'node') { +/*global process */ +define('node/quit', function () { + 'use strict'; + return function (code) { + var draining = 0; + var exit = function () { + if (draining === 0) { + process.exit(code); + } else { + draining -= 1; + } + }; + if (process.stdout.bufferSize) { + draining += 1; + process.stdout.once('drain', exit); + } + if (process.stderr.bufferSize) { + draining += 1; + process.stderr.once('drain', exit); + } + exit(); + }; +}); + +} + +if(env === 'rhino') { +/*global quit */ +define('rhino/quit', function () { + 'use strict'; + return function (code) { + return quit(code); + }; +}); + +} + +if(env === 'xpconnect') { +/*global quit */ +define('xpconnect/quit', function () { + 'use strict'; + return function (code) { + return quit(code); + }; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('browser/print', function () { + function print(msg) { + console.log(msg); + } + + return print; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('node/print', function () { + function print(msg) { + console.log(msg); + } + + return print; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, print: false */ + +define('rhino/print', function () { + return print; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, print: false */ + +define('xpconnect/print', function () { + return print; +}); + +} +/*jslint nomen: false, strict: false */ +/*global define: false */ + +define('logger', ['env!env/print'], function (print) { + var logger = { + TRACE: 0, + INFO: 1, + WARN: 2, + ERROR: 3, + SILENT: 4, + level: 0, + logPrefix: "", + + logLevel: function( level ) { + this.level = level; + }, + + trace: function (message) { + if (this.level <= this.TRACE) { + this._print(message); + } + }, + + info: function (message) { + if (this.level <= this.INFO) { + this._print(message); + } + }, + + warn: function (message) { + if (this.level <= this.WARN) { + this._print(message); + } + }, + + error: function (message) { + if (this.level <= this.ERROR) { + this._print(message); + } + }, + + _print: function (message) { + this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message); + }, + + _sysPrint: function (message) { + print(message); + } + }; + + return logger; +}); +//Just a blank file to use when building the optimizer with the optimizer, +//so that the build does not attempt to inline some env modules, +//like Node's fs and path. + +(function webpackUniversalModuleDefinition(root, factory) { +/* istanbul ignore next */ + if(typeof define === 'function' && define.amd) + define('esprima', [], factory); +/* istanbul ignore next */ + else if(typeof exports === 'object') + exports["esprima"] = factory(); + else + root["esprima"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/* istanbul ignore if */ +/******/ 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__) { + + "use strict"; + /* + Copyright JS Foundation and other contributors, https://js.foundation/ + + 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. + + 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 <COPYRIGHT HOLDER> 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. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var comment_handler_1 = __webpack_require__(1); + var jsx_parser_1 = __webpack_require__(3); + var parser_1 = __webpack_require__(8); + var tokenizer_1 = __webpack_require__(15); + function parse(code, options, delegate) { + var commentHandler = null; + var proxyDelegate = function (node, metadata) { + if (delegate) { + delegate(node, metadata); + } + if (commentHandler) { + commentHandler.visit(node, metadata); + } + }; + var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; + var collectComment = false; + if (options) { + collectComment = (typeof options.comment === 'boolean' && options.comment); + var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); + if (collectComment || attachComment) { + commentHandler = new comment_handler_1.CommentHandler(); + commentHandler.attach = attachComment; + options.comment = true; + parserDelegate = proxyDelegate; + } + } + var isModule = false; + if (options && typeof options.sourceType === 'string') { + isModule = (options.sourceType === 'module'); + } + var parser; + if (options && typeof options.jsx === 'boolean' && options.jsx) { + parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); + } + else { + parser = new parser_1.Parser(code, options, parserDelegate); + } + var program = isModule ? parser.parseModule() : parser.parseScript(); + var ast = program; + if (collectComment && commentHandler) { + ast.comments = commentHandler.comments; + } + if (parser.config.tokens) { + ast.tokens = parser.tokens; + } + if (parser.config.tolerant) { + ast.errors = parser.errorHandler.errors; + } + return ast; + } + exports.parse = parse; + function parseModule(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'module'; + return parse(code, parsingOptions, delegate); + } + exports.parseModule = parseModule; + function parseScript(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'script'; + return parse(code, parsingOptions, delegate); + } + exports.parseScript = parseScript; + function tokenize(code, options, delegate) { + var tokenizer = new tokenizer_1.Tokenizer(code, options); + var tokens; + tokens = []; + try { + while (true) { + var token = tokenizer.getNextToken(); + if (!token) { + break; + } + if (delegate) { + token = delegate(token); + } + tokens.push(token); + } + } + catch (e) { + tokenizer.errorHandler.tolerate(e); + } + if (tokenizer.errorHandler.tolerant) { + tokens.errors = tokenizer.errors(); + } + return tokens; + } + exports.tokenize = tokenize; + var syntax_1 = __webpack_require__(2); + exports.Syntax = syntax_1.Syntax; + // Sync with *.json manifests. + exports.version = '4.0.0'; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + var CommentHandler = (function () { + function CommentHandler() { + this.attach = false; + this.comments = []; + this.stack = []; + this.leading = []; + this.trailing = []; + } + CommentHandler.prototype.insertInnerComments = function (node, metadata) { + // innnerComments for properties empty block + // `function a() {/** comments **\/}` + if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { + var innerComments = []; + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (metadata.end.offset >= entry.start) { + innerComments.unshift(entry.comment); + this.leading.splice(i, 1); + this.trailing.splice(i, 1); + } + } + if (innerComments.length) { + node.innerComments = innerComments; + } + } + }; + CommentHandler.prototype.findTrailingComments = function (metadata) { + var trailingComments = []; + if (this.trailing.length > 0) { + for (var i = this.trailing.length - 1; i >= 0; --i) { + var entry_1 = this.trailing[i]; + if (entry_1.start >= metadata.end.offset) { + trailingComments.unshift(entry_1.comment); + } + } + this.trailing.length = 0; + return trailingComments; + } + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.node.trailingComments) { + var firstComment = entry.node.trailingComments[0]; + if (firstComment && firstComment.range[0] >= metadata.end.offset) { + trailingComments = entry.node.trailingComments; + delete entry.node.trailingComments; + } + } + return trailingComments; + }; + CommentHandler.prototype.findLeadingComments = function (metadata) { + var leadingComments = []; + var target; + while (this.stack.length > 0) { + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.start >= metadata.start.offset) { + target = entry.node; + this.stack.pop(); + } + else { + break; + } + } + if (target) { + var count = target.leadingComments ? target.leadingComments.length : 0; + for (var i = count - 1; i >= 0; --i) { + var comment = target.leadingComments[i]; + if (comment.range[1] <= metadata.start.offset) { + leadingComments.unshift(comment); + target.leadingComments.splice(i, 1); + } + } + if (target.leadingComments && target.leadingComments.length === 0) { + delete target.leadingComments; + } + return leadingComments; + } + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (entry.start <= metadata.start.offset) { + leadingComments.unshift(entry.comment); + this.leading.splice(i, 1); + } + } + return leadingComments; + }; + CommentHandler.prototype.visitNode = function (node, metadata) { + if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { + return; + } + this.insertInnerComments(node, metadata); + var trailingComments = this.findTrailingComments(metadata); + var leadingComments = this.findLeadingComments(metadata); + if (leadingComments.length > 0) { + node.leadingComments = leadingComments; + } + if (trailingComments.length > 0) { + node.trailingComments = trailingComments; + } + this.stack.push({ + node: node, + start: metadata.start.offset + }); + }; + CommentHandler.prototype.visitComment = function (node, metadata) { + var type = (node.type[0] === 'L') ? 'Line' : 'Block'; + var comment = { + type: type, + value: node.value + }; + if (node.range) { + comment.range = node.range; + } + if (node.loc) { + comment.loc = node.loc; + } + this.comments.push(comment); + if (this.attach) { + var entry = { + comment: { + type: type, + value: node.value, + range: [metadata.start.offset, metadata.end.offset] + }, + start: metadata.start.offset + }; + if (node.loc) { + entry.comment.loc = node.loc; + } + node.type = type; + this.leading.push(entry); + this.trailing.push(entry); + } + }; + CommentHandler.prototype.visit = function (node, metadata) { + if (node.type === 'LineComment') { + this.visitComment(node, metadata); + } + else if (node.type === 'BlockComment') { + this.visitComment(node, metadata); + } + else if (this.attach) { + this.visitNode(node, metadata); + } + }; + return CommentHandler; + }()); + exports.CommentHandler = CommentHandler; + + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; +/* istanbul ignore next */ + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var character_1 = __webpack_require__(4); + var JSXNode = __webpack_require__(5); + var jsx_syntax_1 = __webpack_require__(6); + var Node = __webpack_require__(7); + var parser_1 = __webpack_require__(8); + var token_1 = __webpack_require__(13); + var xhtml_entities_1 = __webpack_require__(14); + token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; + token_1.TokenName[101 /* Text */] = 'JSXText'; + // Fully qualified element name, e.g. <svg:path> returns "svg:path" + function getQualifiedElementName(elementName) { + var qualifiedName; + switch (elementName.type) { + case jsx_syntax_1.JSXSyntax.JSXIdentifier: + var id = elementName; + qualifiedName = id.name; + break; + case jsx_syntax_1.JSXSyntax.JSXNamespacedName: + var ns = elementName; + qualifiedName = getQualifiedElementName(ns.namespace) + ':' + + getQualifiedElementName(ns.name); + break; + case jsx_syntax_1.JSXSyntax.JSXMemberExpression: + var expr = elementName; + qualifiedName = getQualifiedElementName(expr.object) + '.' + + getQualifiedElementName(expr.property); + break; + /* istanbul ignore next */ + default: + break; + } + return qualifiedName; + } + var JSXParser = (function (_super) { + __extends(JSXParser, _super); + function JSXParser(code, options, delegate) { + return _super.call(this, code, options, delegate) || this; + } + JSXParser.prototype.parsePrimaryExpression = function () { + return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); + }; + JSXParser.prototype.startJSX = function () { + // Unwind the scanner before the lookahead token. + this.scanner.index = this.startMarker.index; + this.scanner.lineNumber = this.startMarker.line; + this.scanner.lineStart = this.startMarker.index - this.startMarker.column; + }; + JSXParser.prototype.finishJSX = function () { + // Prime the next lookahead. + this.nextToken(); + }; + JSXParser.prototype.reenterJSX = function () { + this.startJSX(); + this.expectJSX('}'); + // Pop the closing '}' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + }; + JSXParser.prototype.createJSXNode = function () { + this.collectComments(); + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.createJSXChildNode = function () { + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.scanXHTMLEntity = function (quote) { + var result = '&'; + var valid = true; + var terminated = false; + var numeric = false; + var hex = false; + while (!this.scanner.eof() && valid && !terminated) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === quote) { + break; + } + terminated = (ch === ';'); + result += ch; + ++this.scanner.index; + if (!terminated) { + switch (result.length) { + case 2: + // e.g. '{' + numeric = (ch === '#'); + break; + case 3: + if (numeric) { + // e.g. 'A' + hex = (ch === 'x'); + valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); + numeric = numeric && !hex; + } + break; + default: + valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); + valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); + break; + } + } + } + if (valid && terminated && result.length > 2) { + // e.g. 'A' becomes just '#x41' + var str = result.substr(1, result.length - 2); + if (numeric && str.length > 1) { + result = String.fromCharCode(parseInt(str.substr(1), 10)); + } + else if (hex && str.length > 2) { + result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); + } + else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { + result = xhtml_entities_1.XHTMLEntities[str]; + } + } + return result; + }; + // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. + JSXParser.prototype.lexJSX = function () { + var cp = this.scanner.source.charCodeAt(this.scanner.index); + // < > / : = { } + if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { + var value = this.scanner.source[this.scanner.index++]; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index - 1, + end: this.scanner.index + }; + } + // " ' + if (cp === 34 || cp === 39) { + var start = this.scanner.index; + var quote = this.scanner.source[this.scanner.index++]; + var str = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index++]; + if (ch === quote) { + break; + } + else if (ch === '&') { + str += this.scanXHTMLEntity(quote); + } + else { + str += ch; + } + } + return { + type: 8 /* StringLiteral */, + value: str, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ... or . + if (cp === 46) { + var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); + var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); + var value = (n1 === 46 && n2 === 46) ? '...' : '.'; + var start = this.scanner.index; + this.scanner.index += value.length; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ` + if (cp === 96) { + // Only placeholder, since it will be rescanned as a real assignment expression. + return { + type: 10 /* Template */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index, + end: this.scanner.index + }; + } + // Identifer can not contain backslash (char code 92). + if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { + var start = this.scanner.index; + ++this.scanner.index; + while (!this.scanner.eof()) { + var ch = this.scanner.source.charCodeAt(this.scanner.index); + if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { + ++this.scanner.index; + } + else if (ch === 45) { + // Hyphen (char code 45) can be part of an identifier. + ++this.scanner.index; + } + else { + break; + } + } + var id = this.scanner.source.slice(start, this.scanner.index); + return { + type: 100 /* Identifier */, + value: id, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + return this.scanner.lex(); + }; + JSXParser.prototype.nextJSXToken = function () { + this.collectComments(); + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var token = this.lexJSX(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + if (this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.nextJSXText = function () { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var start = this.scanner.index; + var text = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === '{' || ch === '<') { + break; + } + ++this.scanner.index; + text += ch; + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.scanner.lineNumber; + if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { + ++this.scanner.index; + } + this.scanner.lineStart = this.scanner.index; + } + } + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + var token = { + type: 101 /* Text */, + value: text, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + if ((text.length > 0) && this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.peekJSXToken = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.lexJSX(); + this.scanner.restoreState(state); + return next; + }; + // Expect the next JSX token to match the specified punctuator. + // If not, an exception will be thrown. + JSXParser.prototype.expectJSX = function (value) { + var token = this.nextJSXToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next JSX token matches the specified punctuator. + JSXParser.prototype.matchJSX = function (value) { + var next = this.peekJSXToken(); + return next.type === 7 /* Punctuator */ && next.value === value; + }; + JSXParser.prototype.parseJSXIdentifier = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 100 /* Identifier */) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); + }; + JSXParser.prototype.parseJSXElementName = function () { + var node = this.createJSXNode(); + var elementName = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = elementName; + this.expectJSX(':'); + var name_1 = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); + } + else if (this.matchJSX('.')) { + while (this.matchJSX('.')) { + var object = elementName; + this.expectJSX('.'); + var property = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); + } + } + return elementName; + }; + JSXParser.prototype.parseJSXAttributeName = function () { + var node = this.createJSXNode(); + var attributeName; + var identifier = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = identifier; + this.expectJSX(':'); + var name_2 = this.parseJSXIdentifier(); + attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); + } + else { + attributeName = identifier; + } + return attributeName; + }; + JSXParser.prototype.parseJSXStringLiteralAttribute = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 8 /* StringLiteral */) { + this.throwUnexpectedToken(token); + } + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + JSXParser.prototype.parseJSXExpressionAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.finishJSX(); + if (this.match('}')) { + this.tolerateError('JSX attributes must only be assigned a non-empty expression'); + } + var expression = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXAttributeValue = function () { + return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : + this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); + }; + JSXParser.prototype.parseJSXNameValueAttribute = function () { + var node = this.createJSXNode(); + var name = this.parseJSXAttributeName(); + var value = null; + if (this.matchJSX('=')) { + this.expectJSX('='); + value = this.parseJSXAttributeValue(); + } + return this.finalize(node, new JSXNode.JSXAttribute(name, value)); + }; + JSXParser.prototype.parseJSXSpreadAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.expectJSX('...'); + this.finishJSX(); + var argument = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); + }; + JSXParser.prototype.parseJSXAttributes = function () { + var attributes = []; + while (!this.matchJSX('/') && !this.matchJSX('>')) { + var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : + this.parseJSXNameValueAttribute(); + attributes.push(attribute); + } + return attributes; + }; + JSXParser.prototype.parseJSXOpeningElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXBoundaryElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + if (this.matchJSX('/')) { + this.expectJSX('/'); + var name_3 = this.parseJSXElementName(); + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); + } + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXEmptyExpression = function () { + var node = this.createJSXChildNode(); + this.collectComments(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + return this.finalize(node, new JSXNode.JSXEmptyExpression()); + }; + JSXParser.prototype.parseJSXExpressionContainer = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + var expression; + if (this.matchJSX('}')) { + expression = this.parseJSXEmptyExpression(); + this.expectJSX('}'); + } + else { + this.finishJSX(); + expression = this.parseAssignmentExpression(); + this.reenterJSX(); + } + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXChildren = function () { + var children = []; + while (!this.scanner.eof()) { + var node = this.createJSXChildNode(); + var token = this.nextJSXText(); + if (token.start < token.end) { + var raw = this.getTokenRaw(token); + var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); + children.push(child); + } + if (this.scanner.source[this.scanner.index] === '{') { + var container = this.parseJSXExpressionContainer(); + children.push(container); + } + else { + break; + } + } + return children; + }; + JSXParser.prototype.parseComplexJSXElement = function (el) { + var stack = []; + while (!this.scanner.eof()) { + el.children = el.children.concat(this.parseJSXChildren()); + var node = this.createJSXChildNode(); + var element = this.parseJSXBoundaryElement(); + if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { + var opening = element; + if (opening.selfClosing) { + var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); + el.children.push(child); + } + else { + stack.push(el); + el = { node: node, opening: opening, closing: null, children: [] }; + } + } + if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { + el.closing = element; + var open_1 = getQualifiedElementName(el.opening.name); + var close_1 = getQualifiedElementName(el.closing.name); + if (open_1 !== close_1) { + this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); + } + if (stack.length > 0) { + var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); + el = stack[stack.length - 1]; + el.children.push(child); + stack.pop(); + } + else { + break; + } + } + } + return el; + }; + JSXParser.prototype.parseJSXElement = function () { + var node = this.createJSXNode(); + var opening = this.parseJSXOpeningElement(); + var children = []; + var closing = null; + if (!opening.selfClosing) { + var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); + children = el.children; + closing = el.closing; + } + return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); + }; + JSXParser.prototype.parseJSXRoot = function () { + // Pop the opening '<' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + this.startJSX(); + var element = this.parseJSXElement(); + this.finishJSX(); + return element; + }; + JSXParser.prototype.isStartOfExpression = function () { + return _super.prototype.isStartOfExpression.call(this) || this.match('<'); + }; + return JSXParser; + }(parser_1.Parser)); + exports.JSXParser = JSXParser; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // See also tools/generate-unicode-regex.js. + var Regex = { + // Unicode v8.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // Unicode v8.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + exports.Character = { + /* tslint:disable:no-bitwise */ + fromCodePoint: function (cp) { + return (cp < 0x10000) ? String.fromCharCode(cp) : + String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); + }, + // https://tc39.github.io/ecma262/#sec-white-space + isWhiteSpace: function (cp) { + return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || + (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); + }, + // https://tc39.github.io/ecma262/#sec-line-terminators + isLineTerminator: function (cp) { + return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); + }, + // https://tc39.github.io/ecma262/#sec-names-and-keywords + isIdentifierStart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); + }, + isIdentifierPart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp >= 0x30 && cp <= 0x39) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); + }, + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + isDecimalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39); // 0..9 + }, + isHexDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x46) || + (cp >= 0x61 && cp <= 0x66); // a..f + }, + isOctalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x37); // 0..7 + } + }; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var jsx_syntax_1 = __webpack_require__(6); + /* tslint:disable:max-classes-per-file */ + var JSXClosingElement = (function () { + function JSXClosingElement(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; + this.name = name; + } + return JSXClosingElement; + }()); + exports.JSXClosingElement = JSXClosingElement; + var JSXElement = (function () { + function JSXElement(openingElement, children, closingElement) { + this.type = jsx_syntax_1.JSXSyntax.JSXElement; + this.openingElement = openingElement; + this.children = children; + this.closingElement = closingElement; + } + return JSXElement; + }()); + exports.JSXElement = JSXElement; + var JSXEmptyExpression = (function () { + function JSXEmptyExpression() { + this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; + } + return JSXEmptyExpression; + }()); + exports.JSXEmptyExpression = JSXEmptyExpression; + var JSXExpressionContainer = (function () { + function JSXExpressionContainer(expression) { + this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; + this.expression = expression; + } + return JSXExpressionContainer; + }()); + exports.JSXExpressionContainer = JSXExpressionContainer; + var JSXIdentifier = (function () { + function JSXIdentifier(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; + this.name = name; + } + return JSXIdentifier; + }()); + exports.JSXIdentifier = JSXIdentifier; + var JSXMemberExpression = (function () { + function JSXMemberExpression(object, property) { + this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; + this.object = object; + this.property = property; + } + return JSXMemberExpression; + }()); + exports.JSXMemberExpression = JSXMemberExpression; + var JSXAttribute = (function () { + function JSXAttribute(name, value) { + this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; + this.name = name; + this.value = value; + } + return JSXAttribute; + }()); + exports.JSXAttribute = JSXAttribute; + var JSXNamespacedName = (function () { + function JSXNamespacedName(namespace, name) { + this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; + this.namespace = namespace; + this.name = name; + } + return JSXNamespacedName; + }()); + exports.JSXNamespacedName = JSXNamespacedName; + var JSXOpeningElement = (function () { + function JSXOpeningElement(name, selfClosing, attributes) { + this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; + this.name = name; + this.selfClosing = selfClosing; + this.attributes = attributes; + } + return JSXOpeningElement; + }()); + exports.JSXOpeningElement = JSXOpeningElement; + var JSXSpreadAttribute = (function () { + function JSXSpreadAttribute(argument) { + this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; + this.argument = argument; + } + return JSXSpreadAttribute; + }()); + exports.JSXSpreadAttribute = JSXSpreadAttribute; + var JSXText = (function () { + function JSXText(value, raw) { + this.type = jsx_syntax_1.JSXSyntax.JSXText; + this.value = value; + this.raw = raw; + } + return JSXText; + }()); + exports.JSXText = JSXText; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSXSyntax = { + JSXAttribute: 'JSXAttribute', + JSXClosingElement: 'JSXClosingElement', + JSXElement: 'JSXElement', + JSXEmptyExpression: 'JSXEmptyExpression', + JSXExpressionContainer: 'JSXExpressionContainer', + JSXIdentifier: 'JSXIdentifier', + JSXMemberExpression: 'JSXMemberExpression', + JSXNamespacedName: 'JSXNamespacedName', + JSXOpeningElement: 'JSXOpeningElement', + JSXSpreadAttribute: 'JSXSpreadAttribute', + JSXText: 'JSXText' + }; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + /* tslint:disable:max-classes-per-file */ + var ArrayExpression = (function () { + function ArrayExpression(elements) { + this.type = syntax_1.Syntax.ArrayExpression; + this.elements = elements; + } + return ArrayExpression; + }()); + exports.ArrayExpression = ArrayExpression; + var ArrayPattern = (function () { + function ArrayPattern(elements) { + this.type = syntax_1.Syntax.ArrayPattern; + this.elements = elements; + } + return ArrayPattern; + }()); + exports.ArrayPattern = ArrayPattern; + var ArrowFunctionExpression = (function () { + function ArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = false; + } + return ArrowFunctionExpression; + }()); + exports.ArrowFunctionExpression = ArrowFunctionExpression; + var AssignmentExpression = (function () { + function AssignmentExpression(operator, left, right) { + this.type = syntax_1.Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return AssignmentExpression; + }()); + exports.AssignmentExpression = AssignmentExpression; + var AssignmentPattern = (function () { + function AssignmentPattern(left, right) { + this.type = syntax_1.Syntax.AssignmentPattern; + this.left = left; + this.right = right; + } + return AssignmentPattern; + }()); + exports.AssignmentPattern = AssignmentPattern; + var AsyncArrowFunctionExpression = (function () { + function AsyncArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = true; + } + return AsyncArrowFunctionExpression; + }()); + exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; + var AsyncFunctionDeclaration = (function () { + function AsyncFunctionDeclaration(id, params, body) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionDeclaration; + }()); + exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; + var AsyncFunctionExpression = (function () { + function AsyncFunctionExpression(id, params, body) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionExpression; + }()); + exports.AsyncFunctionExpression = AsyncFunctionExpression; + var AwaitExpression = (function () { + function AwaitExpression(argument) { + this.type = syntax_1.Syntax.AwaitExpression; + this.argument = argument; + } + return AwaitExpression; + }()); + exports.AwaitExpression = AwaitExpression; + var BinaryExpression = (function () { + function BinaryExpression(operator, left, right) { + var logical = (operator === '||' || operator === '&&'); + this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return BinaryExpression; + }()); + exports.BinaryExpression = BinaryExpression; + var BlockStatement = (function () { + function BlockStatement(body) { + this.type = syntax_1.Syntax.BlockStatement; + this.body = body; + } + return BlockStatement; + }()); + exports.BlockStatement = BlockStatement; + var BreakStatement = (function () { + function BreakStatement(label) { + this.type = syntax_1.Syntax.BreakStatement; + this.label = label; + } + return BreakStatement; + }()); + exports.BreakStatement = BreakStatement; + var CallExpression = (function () { + function CallExpression(callee, args) { + this.type = syntax_1.Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + } + return CallExpression; + }()); + exports.CallExpression = CallExpression; + var CatchClause = (function () { + function CatchClause(param, body) { + this.type = syntax_1.Syntax.CatchClause; + this.param = param; + this.body = body; + } + return CatchClause; + }()); + exports.CatchClause = CatchClause; + var ClassBody = (function () { + function ClassBody(body) { + this.type = syntax_1.Syntax.ClassBody; + this.body = body; + } + return ClassBody; + }()); + exports.ClassBody = ClassBody; + var ClassDeclaration = (function () { + function ClassDeclaration(id, superClass, body) { + this.type = syntax_1.Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassDeclaration; + }()); + exports.ClassDeclaration = ClassDeclaration; + var ClassExpression = (function () { + function ClassExpression(id, superClass, body) { + this.type = syntax_1.Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassExpression; + }()); + exports.ClassExpression = ClassExpression; + var ComputedMemberExpression = (function () { + function ComputedMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = true; + this.object = object; + this.property = property; + } + return ComputedMemberExpression; + }()); + exports.ComputedMemberExpression = ComputedMemberExpression; + var ConditionalExpression = (function () { + function ConditionalExpression(test, consequent, alternate) { + this.type = syntax_1.Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return ConditionalExpression; + }()); + exports.ConditionalExpression = ConditionalExpression; + var ContinueStatement = (function () { + function ContinueStatement(label) { + this.type = syntax_1.Syntax.ContinueStatement; + this.label = label; + } + return ContinueStatement; + }()); + exports.ContinueStatement = ContinueStatement; + var DebuggerStatement = (function () { + function DebuggerStatement() { + this.type = syntax_1.Syntax.DebuggerStatement; + } + return DebuggerStatement; + }()); + exports.DebuggerStatement = DebuggerStatement; + var Directive = (function () { + function Directive(expression, directive) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + this.directive = directive; + } + return Directive; + }()); + exports.Directive = Directive; + var DoWhileStatement = (function () { + function DoWhileStatement(body, test) { + this.type = syntax_1.Syntax.DoWhileStatement; + this.body = body; + this.test = test; + } + return DoWhileStatement; + }()); + exports.DoWhileStatement = DoWhileStatement; + var EmptyStatement = (function () { + function EmptyStatement() { + this.type = syntax_1.Syntax.EmptyStatement; + } + return EmptyStatement; + }()); + exports.EmptyStatement = EmptyStatement; + var ExportAllDeclaration = (function () { + function ExportAllDeclaration(source) { + this.type = syntax_1.Syntax.ExportAllDeclaration; + this.source = source; + } + return ExportAllDeclaration; + }()); + exports.ExportAllDeclaration = ExportAllDeclaration; + var ExportDefaultDeclaration = (function () { + function ExportDefaultDeclaration(declaration) { + this.type = syntax_1.Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + } + return ExportDefaultDeclaration; + }()); + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + var ExportNamedDeclaration = (function () { + function ExportNamedDeclaration(declaration, specifiers, source) { + this.type = syntax_1.Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = source; + } + return ExportNamedDeclaration; + }()); + exports.ExportNamedDeclaration = ExportNamedDeclaration; + var ExportSpecifier = (function () { + function ExportSpecifier(local, exported) { + this.type = syntax_1.Syntax.ExportSpecifier; + this.exported = exported; + this.local = local; + } + return ExportSpecifier; + }()); + exports.ExportSpecifier = ExportSpecifier; + var ExpressionStatement = (function () { + function ExpressionStatement(expression) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + } + return ExpressionStatement; + }()); + exports.ExpressionStatement = ExpressionStatement; + var ForInStatement = (function () { + function ForInStatement(left, right, body) { + this.type = syntax_1.Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + } + return ForInStatement; + }()); + exports.ForInStatement = ForInStatement; + var ForOfStatement = (function () { + function ForOfStatement(left, right, body) { + this.type = syntax_1.Syntax.ForOfStatement; + this.left = left; + this.right = right; + this.body = body; + } + return ForOfStatement; + }()); + exports.ForOfStatement = ForOfStatement; + var ForStatement = (function () { + function ForStatement(init, test, update, body) { + this.type = syntax_1.Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + } + return ForStatement; + }()); + exports.ForStatement = ForStatement; + var FunctionDeclaration = (function () { + function FunctionDeclaration(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionDeclaration; + }()); + exports.FunctionDeclaration = FunctionDeclaration; + var FunctionExpression = (function () { + function FunctionExpression(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionExpression; + }()); + exports.FunctionExpression = FunctionExpression; + var Identifier = (function () { + function Identifier(name) { + this.type = syntax_1.Syntax.Identifier; + this.name = name; + } + return Identifier; + }()); + exports.Identifier = Identifier; + var IfStatement = (function () { + function IfStatement(test, consequent, alternate) { + this.type = syntax_1.Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return IfStatement; + }()); + exports.IfStatement = IfStatement; + var ImportDeclaration = (function () { + function ImportDeclaration(specifiers, source) { + this.type = syntax_1.Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = source; + } + return ImportDeclaration; + }()); + exports.ImportDeclaration = ImportDeclaration; + var ImportDefaultSpecifier = (function () { + function ImportDefaultSpecifier(local) { + this.type = syntax_1.Syntax.ImportDefaultSpecifier; + this.local = local; + } + return ImportDefaultSpecifier; + }()); + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + var ImportNamespaceSpecifier = (function () { + function ImportNamespaceSpecifier(local) { + this.type = syntax_1.Syntax.ImportNamespaceSpecifier; + this.local = local; + } + return ImportNamespaceSpecifier; + }()); + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + var ImportSpecifier = (function () { + function ImportSpecifier(local, imported) { + this.type = syntax_1.Syntax.ImportSpecifier; + this.local = local; + this.imported = imported; + } + return ImportSpecifier; + }()); + exports.ImportSpecifier = ImportSpecifier; + var LabeledStatement = (function () { + function LabeledStatement(label, body) { + this.type = syntax_1.Syntax.LabeledStatement; + this.label = label; + this.body = body; + } + return LabeledStatement; + }()); + exports.LabeledStatement = LabeledStatement; + var Literal = (function () { + function Literal(value, raw) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + } + return Literal; + }()); + exports.Literal = Literal; + var MetaProperty = (function () { + function MetaProperty(meta, property) { + this.type = syntax_1.Syntax.MetaProperty; + this.meta = meta; + this.property = property; + } + return MetaProperty; + }()); + exports.MetaProperty = MetaProperty; + var MethodDefinition = (function () { + function MethodDefinition(key, computed, value, kind, isStatic) { + this.type = syntax_1.Syntax.MethodDefinition; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.static = isStatic; + } + return MethodDefinition; + }()); + exports.MethodDefinition = MethodDefinition; + var Module = (function () { + function Module(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'module'; + } + return Module; + }()); + exports.Module = Module; + var NewExpression = (function () { + function NewExpression(callee, args) { + this.type = syntax_1.Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + } + return NewExpression; + }()); + exports.NewExpression = NewExpression; + var ObjectExpression = (function () { + function ObjectExpression(properties) { + this.type = syntax_1.Syntax.ObjectExpression; + this.properties = properties; + } + return ObjectExpression; + }()); + exports.ObjectExpression = ObjectExpression; + var ObjectPattern = (function () { + function ObjectPattern(properties) { + this.type = syntax_1.Syntax.ObjectPattern; + this.properties = properties; + } + return ObjectPattern; + }()); + exports.ObjectPattern = ObjectPattern; + var Property = (function () { + function Property(kind, key, computed, value, method, shorthand) { + this.type = syntax_1.Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + } + return Property; + }()); + exports.Property = Property; + var RegexLiteral = (function () { + function RegexLiteral(value, raw, pattern, flags) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + this.regex = { pattern: pattern, flags: flags }; + } + return RegexLiteral; + }()); + exports.RegexLiteral = RegexLiteral; + var RestElement = (function () { + function RestElement(argument) { + this.type = syntax_1.Syntax.RestElement; + this.argument = argument; + } + return RestElement; + }()); + exports.RestElement = RestElement; + var ReturnStatement = (function () { + function ReturnStatement(argument) { + this.type = syntax_1.Syntax.ReturnStatement; + this.argument = argument; + } + return ReturnStatement; + }()); + exports.ReturnStatement = ReturnStatement; + var Script = (function () { + function Script(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'script'; + } + return Script; + }()); + exports.Script = Script; + var SequenceExpression = (function () { + function SequenceExpression(expressions) { + this.type = syntax_1.Syntax.SequenceExpression; + this.expressions = expressions; + } + return SequenceExpression; + }()); + exports.SequenceExpression = SequenceExpression; + var SpreadElement = (function () { + function SpreadElement(argument) { + this.type = syntax_1.Syntax.SpreadElement; + this.argument = argument; + } + return SpreadElement; + }()); + exports.SpreadElement = SpreadElement; + var StaticMemberExpression = (function () { + function StaticMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = false; + this.object = object; + this.property = property; + } + return StaticMemberExpression; + }()); + exports.StaticMemberExpression = StaticMemberExpression; + var Super = (function () { + function Super() { + this.type = syntax_1.Syntax.Super; + } + return Super; + }()); + exports.Super = Super; + var SwitchCase = (function () { + function SwitchCase(test, consequent) { + this.type = syntax_1.Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + } + return SwitchCase; + }()); + exports.SwitchCase = SwitchCase; + var SwitchStatement = (function () { + function SwitchStatement(discriminant, cases) { + this.type = syntax_1.Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + } + return SwitchStatement; + }()); + exports.SwitchStatement = SwitchStatement; + var TaggedTemplateExpression = (function () { + function TaggedTemplateExpression(tag, quasi) { + this.type = syntax_1.Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + } + return TaggedTemplateExpression; + }()); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + var TemplateElement = (function () { + function TemplateElement(value, tail) { + this.type = syntax_1.Syntax.TemplateElement; + this.value = value; + this.tail = tail; + } + return TemplateElement; + }()); + exports.TemplateElement = TemplateElement; + var TemplateLiteral = (function () { + function TemplateLiteral(quasis, expressions) { + this.type = syntax_1.Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + } + return TemplateLiteral; + }()); + exports.TemplateLiteral = TemplateLiteral; + var ThisExpression = (function () { + function ThisExpression() { + this.type = syntax_1.Syntax.ThisExpression; + } + return ThisExpression; + }()); + exports.ThisExpression = ThisExpression; + var ThrowStatement = (function () { + function ThrowStatement(argument) { + this.type = syntax_1.Syntax.ThrowStatement; + this.argument = argument; + } + return ThrowStatement; + }()); + exports.ThrowStatement = ThrowStatement; + var TryStatement = (function () { + function TryStatement(block, handler, finalizer) { + this.type = syntax_1.Syntax.TryStatement; + this.block = block; + this.handler = handler; + this.finalizer = finalizer; + } + return TryStatement; + }()); + exports.TryStatement = TryStatement; + var UnaryExpression = (function () { + function UnaryExpression(operator, argument) { + this.type = syntax_1.Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + } + return UnaryExpression; + }()); + exports.UnaryExpression = UnaryExpression; + var UpdateExpression = (function () { + function UpdateExpression(operator, argument, prefix) { + this.type = syntax_1.Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = prefix; + } + return UpdateExpression; + }()); + exports.UpdateExpression = UpdateExpression; + var VariableDeclaration = (function () { + function VariableDeclaration(declarations, kind) { + this.type = syntax_1.Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + } + return VariableDeclaration; + }()); + exports.VariableDeclaration = VariableDeclaration; + var VariableDeclarator = (function () { + function VariableDeclarator(id, init) { + this.type = syntax_1.Syntax.VariableDeclarator; + this.id = id; + this.init = init; + } + return VariableDeclarator; + }()); + exports.VariableDeclarator = VariableDeclarator; + var WhileStatement = (function () { + function WhileStatement(test, body) { + this.type = syntax_1.Syntax.WhileStatement; + this.test = test; + this.body = body; + } + return WhileStatement; + }()); + exports.WhileStatement = WhileStatement; + var WithStatement = (function () { + function WithStatement(object, body) { + this.type = syntax_1.Syntax.WithStatement; + this.object = object; + this.body = body; + } + return WithStatement; + }()); + exports.WithStatement = WithStatement; + var YieldExpression = (function () { + function YieldExpression(argument, delegate) { + this.type = syntax_1.Syntax.YieldExpression; + this.argument = argument; + this.delegate = delegate; + } + return YieldExpression; + }()); + exports.YieldExpression = YieldExpression; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var error_handler_1 = __webpack_require__(10); + var messages_1 = __webpack_require__(11); + var Node = __webpack_require__(7); + var scanner_1 = __webpack_require__(12); + var syntax_1 = __webpack_require__(2); + var token_1 = __webpack_require__(13); + var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; + var Parser = (function () { + function Parser(code, options, delegate) { + if (options === void 0) { options = {}; } + this.config = { + range: (typeof options.range === 'boolean') && options.range, + loc: (typeof options.loc === 'boolean') && options.loc, + source: null, + tokens: (typeof options.tokens === 'boolean') && options.tokens, + comment: (typeof options.comment === 'boolean') && options.comment, + tolerant: (typeof options.tolerant === 'boolean') && options.tolerant + }; + if (this.config.loc && options.source && options.source !== null) { + this.config.source = String(options.source); + } + this.delegate = delegate; + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = this.config.tolerant; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = this.config.comment; + this.operatorPrecedence = { + ')': 0, + ';': 0, + ',': 0, + '=': 0, + ']': 0, + '||': 1, + '&&': 2, + '|': 3, + '^': 4, + '&': 5, + '==': 6, + '!=': 6, + '===': 6, + '!==': 6, + '<': 7, + '>': 7, + '<=': 7, + '>=': 7, + '<<': 8, + '>>': 8, + '>>>': 8, + '+': 9, + '-': 9, + '*': 11, + '/': 11, + '%': 11 + }; + this.lookahead = { + type: 2 /* EOF */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: 0, + start: 0, + end: 0 + }; + this.hasLineTerminator = false; + this.context = { + isModule: false, + await: false, + allowIn: true, + allowStrictDirective: true, + allowYield: true, + firstCoverInitializedNameError: null, + isAssignmentTarget: false, + isBindingElement: false, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + labelSet: {}, + strict: false + }; + this.tokens = []; + this.startMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.lastMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.nextToken(); + this.lastMarker = { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + } + Parser.prototype.throwError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + throw this.errorHandler.createError(index, line, column, msg); + }; + Parser.prototype.tolerateError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.scanner.lineNumber; + var column = this.lastMarker.column + 1; + this.errorHandler.tolerateError(index, line, column, msg); + }; + // Throw an exception because of the token. + Parser.prototype.unexpectedTokenError = function (token, message) { + var msg = message || messages_1.Messages.UnexpectedToken; + var value; + if (token) { + if (!message) { + msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : + (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : + (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : + (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : + (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : + messages_1.Messages.UnexpectedToken; + if (token.type === 4 /* Keyword */) { + if (this.scanner.isFutureReservedWord(token.value)) { + msg = messages_1.Messages.UnexpectedReserved; + } + else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { + msg = messages_1.Messages.StrictReservedWord; + } + } + } + value = token.value; + } + else { + value = 'ILLEGAL'; + } + msg = msg.replace('%0', value); + if (token && typeof token.lineNumber === 'number') { + var index = token.start; + var line = token.lineNumber; + var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; + var column = token.start - lastMarkerLineStart + 1; + return this.errorHandler.createError(index, line, column, msg); + } + else { + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + return this.errorHandler.createError(index, line, column, msg); + } + }; + Parser.prototype.throwUnexpectedToken = function (token, message) { + throw this.unexpectedTokenError(token, message); + }; + Parser.prototype.tolerateUnexpectedToken = function (token, message) { + this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); + }; + Parser.prototype.collectComments = function () { + if (!this.config.comment) { + this.scanner.scanComments(); + } + else { + var comments = this.scanner.scanComments(); + if (comments.length > 0 && this.delegate) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var node = void 0; + node = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: this.scanner.source.slice(e.slice[0], e.slice[1]) + }; + if (this.config.range) { + node.range = e.range; + } + if (this.config.loc) { + node.loc = e.loc; + } + var metadata = { + start: { + line: e.loc.start.line, + column: e.loc.start.column, + offset: e.range[0] + }, + end: { + line: e.loc.end.line, + column: e.loc.end.column, + offset: e.range[1] + } + }; + this.delegate(node, metadata); + } + } + } + }; + // From internal representation to an external structure + Parser.prototype.getTokenRaw = function (token) { + return this.scanner.source.slice(token.start, token.end); + }; + Parser.prototype.convertToken = function (token) { + var t = { + type: token_1.TokenName[token.type], + value: this.getTokenRaw(token) + }; + if (this.config.range) { + t.range = [token.start, token.end]; + } + if (this.config.loc) { + t.loc = { + start: { + line: this.startMarker.line, + column: this.startMarker.column + }, + end: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + } + }; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + t.regex = { pattern: pattern, flags: flags }; + } + return t; + }; + Parser.prototype.nextToken = function () { + var token = this.lookahead; + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + this.collectComments(); + if (this.scanner.index !== this.startMarker.index) { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + } + var next = this.scanner.lex(); + this.hasLineTerminator = (token.lineNumber !== next.lineNumber); + if (next && this.context.strict && next.type === 3 /* Identifier */) { + if (this.scanner.isStrictModeReservedWord(next.value)) { + next.type = 4 /* Keyword */; + } + } + this.lookahead = next; + if (this.config.tokens && next.type !== 2 /* EOF */) { + this.tokens.push(this.convertToken(next)); + } + return token; + }; + Parser.prototype.nextRegexToken = function () { + this.collectComments(); + var token = this.scanner.scanRegExp(); + if (this.config.tokens) { + // Pop the previous token, '/' or '/=' + // This is added from the lookahead token. + this.tokens.pop(); + this.tokens.push(this.convertToken(token)); + } + // Prime the next lookahead. + this.lookahead = token; + this.nextToken(); + return token; + }; + Parser.prototype.createNode = function () { + return { + index: this.startMarker.index, + line: this.startMarker.line, + column: this.startMarker.column + }; + }; + Parser.prototype.startNode = function (token) { + return { + index: token.start, + line: token.lineNumber, + column: token.start - token.lineStart + }; + }; + Parser.prototype.finalize = function (marker, node) { + if (this.config.range) { + node.range = [marker.index, this.lastMarker.index]; + } + if (this.config.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.column, + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column + } + }; + if (this.config.source) { + node.loc.source = this.config.source; + } + } + if (this.delegate) { + var metadata = { + start: { + line: marker.line, + column: marker.column, + offset: marker.index + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column, + offset: this.lastMarker.index + } + }; + this.delegate(node, metadata); + } + return node; + }; + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + Parser.prototype.expect = function (value) { + var token = this.nextToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). + Parser.prototype.expectCommaSeparator = function () { + if (this.config.tolerant) { + var token = this.lookahead; + if (token.type === 7 /* Punctuator */ && token.value === ',') { + this.nextToken(); + } + else if (token.type === 7 /* Punctuator */ && token.value === ';') { + this.nextToken(); + this.tolerateUnexpectedToken(token); + } + else { + this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); + } + } + else { + this.expect(','); + } + }; + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + Parser.prototype.expectKeyword = function (keyword) { + var token = this.nextToken(); + if (token.type !== 4 /* Keyword */ || token.value !== keyword) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next token matches the specified punctuator. + Parser.prototype.match = function (value) { + return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; + }; + // Return true if the next token matches the specified keyword + Parser.prototype.matchKeyword = function (keyword) { + return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; + }; + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + Parser.prototype.matchContextualKeyword = function (keyword) { + return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; + }; + // Return true if the next token is an assignment operator + Parser.prototype.matchAssign = function () { + if (this.lookahead.type !== 7 /* Punctuator */) { + return false; + } + var op = this.lookahead.value; + return op === '=' || + op === '*=' || + op === '**=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + }; + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + Parser.prototype.isolateCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + if (this.context.firstCoverInitializedNameError !== null) { + this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); + } + this.context.isBindingElement = previousIsBindingElement; + this.context.isAssignmentTarget = previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; + return result; + }; + Parser.prototype.inheritCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; + this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; + return result; + }; + Parser.prototype.consumeSemicolon = function () { + if (this.match(';')) { + this.nextToken(); + } + else if (!this.hasLineTerminator) { + if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { + this.throwUnexpectedToken(this.lookahead); + } + this.lastMarker.index = this.startMarker.index; + this.lastMarker.line = this.startMarker.line; + this.lastMarker.column = this.startMarker.column; + } + }; + // https://tc39.github.io/ecma262/#sec-primary-expression + Parser.prototype.parsePrimaryExpression = function () { + var node = this.createNode(); + var expr; + var token, raw; + switch (this.lookahead.type) { + case 3 /* Identifier */: + if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { + this.tolerateUnexpectedToken(this.lookahead); + } + expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); + break; + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + if (this.context.strict && this.lookahead.octal) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 1 /* BooleanLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); + break; + case 5 /* NullLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(null, raw)); + break; + case 10 /* Template */: + expr = this.parseTemplateLiteral(); + break; + case 7 /* Punctuator */: + switch (this.lookahead.value) { + case '(': + this.context.isBindingElement = false; + expr = this.inheritCoverGrammar(this.parseGroupExpression); + break; + case '[': + expr = this.inheritCoverGrammar(this.parseArrayInitializer); + break; + case '{': + expr = this.inheritCoverGrammar(this.parseObjectInitializer); + break; + case '/': + case '/=': + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.scanner.index = this.startMarker.index; + token = this.nextRegexToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + break; + case 4 /* Keyword */: + if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseIdentifierName(); + } + else if (!this.context.strict && this.matchKeyword('let')) { + expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); + } + else { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + if (this.matchKeyword('function')) { + expr = this.parseFunctionExpression(); + } + else if (this.matchKeyword('this')) { + this.nextToken(); + expr = this.finalize(node, new Node.ThisExpression()); + } + else if (this.matchKeyword('class')) { + expr = this.parseClassExpression(); + } + else { + expr = this.throwUnexpectedToken(this.nextToken()); + } + } + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-array-initializer + Parser.prototype.parseSpreadElement = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadElement(arg)); + }; + Parser.prototype.parseArrayInitializer = function () { + var node = this.createNode(); + var elements = []; + this.expect('['); + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else if (this.match('...')) { + var element = this.parseSpreadElement(); + if (!this.match(']')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.expect(','); + } + elements.push(element); + } + else { + elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayExpression(elements)); + }; + // https://tc39.github.io/ecma262/#sec-object-initializer + Parser.prototype.parsePropertyMethod = function (params) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = params.simple; + var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); + if (this.context.strict && params.firstRestricted) { + this.tolerateUnexpectedToken(params.firstRestricted, params.message); + } + if (this.context.strict && params.stricted) { + this.tolerateUnexpectedToken(params.stricted, params.message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + return body; + }; + Parser.prototype.parsePropertyMethodFunction = function () { + var isGenerator = false; + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + Parser.prototype.parsePropertyMethodAsyncFunction = function () { + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = false; + this.context.await = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); + }; + Parser.prototype.parseObjectPropertyKey = function () { + var node = this.createNode(); + var token = this.nextToken(); + var key; + switch (token.type) { + case 8 /* StringLiteral */: + case 6 /* NumericLiteral */: + if (this.context.strict && token.octal) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); + } + var raw = this.getTokenRaw(token); + key = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 3 /* Identifier */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 4 /* Keyword */: + key = this.finalize(node, new Node.Identifier(token.value)); + break; + case 7 /* Punctuator */: + if (token.value === '[') { + key = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.expect(']'); + } + else { + key = this.throwUnexpectedToken(token); + } + break; + default: + key = this.throwUnexpectedToken(token); + } + return key; + }; + Parser.prototype.isPropertyKey = function (key, value) { + return (key.type === syntax_1.Syntax.Identifier && key.name === value) || + (key.type === syntax_1.Syntax.Literal && key.value === value); + }; + Parser.prototype.parseObjectProperty = function (hasProto) { + var node = this.createNode(); + var token = this.lookahead; + var kind; + var key = null; + var value = null; + var computed = false; + var method = false; + var shorthand = false; + var isAsync = false; + if (token.type === 3 /* Identifier */) { + var id = token.value; + this.nextToken(); + computed = this.match('['); + isAsync = !this.hasLineTerminator && (id === 'async') && + !this.match(':') && !this.match('(') && !this.match('*'); + key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); + } + else if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + else { + if (!key) { + this.throwUnexpectedToken(this.lookahead); + } + kind = 'init'; + if (this.match(':') && !isAsync) { + if (!computed && this.isPropertyKey(key, '__proto__')) { + if (hasProto.value) { + this.tolerateError(messages_1.Messages.DuplicateProtoProperty); + } + hasProto.value = true; + } + this.nextToken(); + value = this.inheritCoverGrammar(this.parseAssignmentExpression); + } + else if (this.match('(')) { + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + else if (token.type === 3 /* Identifier */) { + var id = this.finalize(node, new Node.Identifier(token.value)); + if (this.match('=')) { + this.context.firstCoverInitializedNameError = this.lookahead; + this.nextToken(); + shorthand = true; + var init = this.isolateCoverGrammar(this.parseAssignmentExpression); + value = this.finalize(node, new Node.AssignmentPattern(id, init)); + } + else { + shorthand = true; + value = id; + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectInitializer = function () { + var node = this.createNode(); + this.expect('{'); + var properties = []; + var hasProto = { value: false }; + while (!this.match('}')) { + properties.push(this.parseObjectProperty(hasProto)); + if (!this.match('}')) { + this.expectCommaSeparator(); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectExpression(properties)); + }; + // https://tc39.github.io/ecma262/#sec-template-literals + Parser.prototype.parseTemplateHead = function () { + assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateElement = function () { + if (this.lookahead.type !== 10 /* Template */) { + this.throwUnexpectedToken(); + } + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateLiteral = function () { + var node = this.createNode(); + var expressions = []; + var quasis = []; + var quasi = this.parseTemplateHead(); + quasis.push(quasi); + while (!quasi.tail) { + expressions.push(this.parseExpression()); + quasi = this.parseTemplateElement(); + quasis.push(quasi); + } + return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); + }; + // https://tc39.github.io/ecma262/#sec-grouping-operator + Parser.prototype.reinterpretExpressionAsPattern = function (expr) { + switch (expr.type) { + case syntax_1.Syntax.Identifier: + case syntax_1.Syntax.MemberExpression: + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.AssignmentPattern: + break; + case syntax_1.Syntax.SpreadElement: + expr.type = syntax_1.Syntax.RestElement; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.ArrayExpression: + expr.type = syntax_1.Syntax.ArrayPattern; + for (var i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + this.reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectExpression: + expr.type = syntax_1.Syntax.ObjectPattern; + for (var i = 0; i < expr.properties.length; i++) { + this.reinterpretExpressionAsPattern(expr.properties[i].value); + } + break; + case syntax_1.Syntax.AssignmentExpression: + expr.type = syntax_1.Syntax.AssignmentPattern; + delete expr.operator; + this.reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + }; + Parser.prototype.parseGroupExpression = function () { + var expr; + this.expect('('); + if (this.match(')')) { + this.nextToken(); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [], + async: false + }; + } + else { + var startToken = this.lookahead; + var params = []; + if (this.match('...')) { + expr = this.parseRestElement(params); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + else { + var arrow = false; + this.context.isBindingElement = true; + expr = this.inheritCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + this.context.isAssignmentTarget = false; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + if (this.match(')')) { + this.nextToken(); + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else if (this.match('...')) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + expressions.push(this.parseRestElement(params)); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + this.context.isBindingElement = false; + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else { + expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + } + if (arrow) { + break; + } + } + if (!arrow) { + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + } + if (!arrow) { + this.expect(')'); + if (this.match('=>')) { + if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + if (!arrow) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + if (expr.type === syntax_1.Syntax.SequenceExpression) { + for (var i = 0; i < expr.expressions.length; i++) { + this.reinterpretExpressionAsPattern(expr.expressions[i]); + } + } + else { + this.reinterpretExpressionAsPattern(expr); + } + var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); + expr = { + type: ArrowParameterPlaceHolder, + params: parameters, + async: false + }; + } + } + this.context.isBindingElement = false; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions + Parser.prototype.parseArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.isIdentifierName = function (token) { + return token.type === 3 /* Identifier */ || + token.type === 4 /* Keyword */ || + token.type === 1 /* BooleanLiteral */ || + token.type === 5 /* NullLiteral */; + }; + Parser.prototype.parseIdentifierName = function () { + var node = this.createNode(); + var token = this.nextToken(); + if (!this.isIdentifierName(token)) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseNewExpression = function () { + var node = this.createNode(); + var id = this.parseIdentifierName(); + assert_1.assert(id.name === 'new', 'New expression must start with `new`'); + var expr; + if (this.match('.')) { + this.nextToken(); + if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { + var property = this.parseIdentifierName(); + expr = new Node.MetaProperty(id, property); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); + var args = this.match('(') ? this.parseArguments() : []; + expr = new Node.NewExpression(callee, args); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return this.finalize(node, expr); + }; + Parser.prototype.parseAsyncArgument = function () { + var arg = this.parseAssignmentExpression(); + this.context.firstCoverInitializedNameError = null; + return arg; + }; + Parser.prototype.parseAsyncArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAsyncArgument); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { + var startToken = this.lookahead; + var maybeAsync = this.matchContextualKeyword('async'); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var expr; + if (this.matchKeyword('super') && this.context.inFunctionBody) { + expr = this.createNode(); + this.nextToken(); + expr = this.finalize(expr, new Node.Super()); + if (!this.match('(') && !this.match('.') && !this.match('[')) { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + } + while (true) { + if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); + } + else if (this.match('(')) { + var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); + this.context.isBindingElement = false; + this.context.isAssignmentTarget = false; + var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); + expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); + if (asyncArrow && this.match('=>')) { + for (var i = 0; i < args.length; ++i) { + this.reinterpretExpressionAsPattern(args[i]); + } + expr = { + type: ArrowParameterPlaceHolder, + params: args, + async: true + }; + } + } + else if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + this.context.allowIn = previousAllowIn; + return expr; + }; + Parser.prototype.parseSuper = function () { + var node = this.createNode(); + this.expectKeyword('super'); + if (!this.match('[') && !this.match('.')) { + this.throwUnexpectedToken(this.lookahead); + } + return this.finalize(node, new Node.Super()); + }; + Parser.prototype.parseLeftHandSideExpression = function () { + assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); + var node = this.startNode(this.lookahead); + var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : + this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + while (true) { + if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); + } + else if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-update-expressions + Parser.prototype.parseUpdateExpression = function () { + var expr; + var startToken = this.lookahead; + if (this.match('++') || this.match('--')) { + var node = this.startNode(startToken); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPrefix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + var prefix = true; + expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { + if (this.match('++') || this.match('--')) { + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPostfix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var operator = this.nextToken().value; + var prefix = false; + expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-unary-operators + Parser.prototype.parseAwaitExpression = function () { + var node = this.createNode(); + this.nextToken(); + var argument = this.parseUnaryExpression(); + return this.finalize(node, new Node.AwaitExpression(argument)); + }; + Parser.prototype.parseUnaryExpression = function () { + var expr; + if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || + this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { + var node = this.startNode(this.lookahead); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); + if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { + this.tolerateError(messages_1.Messages.StrictDelete); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else if (this.context.await && this.matchContextualKeyword('await')) { + expr = this.parseAwaitExpression(); + } + else { + expr = this.parseUpdateExpression(); + } + return expr; + }; + Parser.prototype.parseExponentiationExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-exp-operator + // https://tc39.github.io/ecma262/#sec-multiplicative-operators + // https://tc39.github.io/ecma262/#sec-additive-operators + // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators + // https://tc39.github.io/ecma262/#sec-relational-operators + // https://tc39.github.io/ecma262/#sec-equality-operators + // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators + // https://tc39.github.io/ecma262/#sec-binary-logical-operators + Parser.prototype.binaryPrecedence = function (token) { + var op = token.value; + var precedence; + if (token.type === 7 /* Punctuator */) { + precedence = this.operatorPrecedence[op] || 0; + } + else if (token.type === 4 /* Keyword */) { + precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; + } + else { + precedence = 0; + } + return precedence; + }; + Parser.prototype.parseBinaryExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); + var token = this.lookahead; + var prec = this.binaryPrecedence(token); + if (prec > 0) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var markers = [startToken, this.lookahead]; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + var stack = [left, token.value, right]; + var precedences = [prec]; + while (true) { + prec = this.binaryPrecedence(this.lookahead); + if (prec <= 0) { + break; + } + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { + right = stack.pop(); + var operator = stack.pop(); + precedences.pop(); + left = stack.pop(); + markers.pop(); + var node = this.startNode(markers[markers.length - 1]); + stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); + } + // Shift. + stack.push(this.nextToken().value); + precedences.push(prec); + markers.push(this.lookahead); + stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); + } + // Final reduce to clean-up the stack. + var i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + var node = this.startNode(markers.pop()); + var operator = stack[i - 1]; + expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); + i -= 2; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-conditional-operator + Parser.prototype.parseConditionalExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseBinaryExpression); + if (this.match('?')) { + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + this.expect(':'); + var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-assignment-operators + Parser.prototype.checkPatternParam = function (options, param) { + switch (param.type) { + case syntax_1.Syntax.Identifier: + this.validateParam(options, param, param.name); + break; + case syntax_1.Syntax.RestElement: + this.checkPatternParam(options, param.argument); + break; + case syntax_1.Syntax.AssignmentPattern: + this.checkPatternParam(options, param.left); + break; + case syntax_1.Syntax.ArrayPattern: + for (var i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + this.checkPatternParam(options, param.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectPattern: + for (var i = 0; i < param.properties.length; i++) { + this.checkPatternParam(options, param.properties[i].value); + } + break; + default: + break; + } + options.simple = options.simple && (param instanceof Node.Identifier); + }; + Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { + var params = [expr]; + var options; + var asyncArrow = false; + switch (expr.type) { + case syntax_1.Syntax.Identifier: + break; + case ArrowParameterPlaceHolder: + params = expr.params; + asyncArrow = expr.async; + break; + default: + return null; + } + options = { + simple: true, + paramSet: {} + }; + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.AssignmentPattern) { + if (param.right.type === syntax_1.Syntax.YieldExpression) { + if (param.right.argument) { + this.throwUnexpectedToken(this.lookahead); + } + param.right.type = syntax_1.Syntax.Identifier; + param.right.name = 'yield'; + delete param.right.argument; + delete param.right.delegate; + } + } + else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { + this.throwUnexpectedToken(this.lookahead); + } + this.checkPatternParam(options, param); + params[i] = param; + } + if (this.context.strict || !this.context.allowYield) { + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.YieldExpression) { + this.throwUnexpectedToken(this.lookahead); + } + } + } + if (options.message === messages_1.Messages.StrictParamDupe) { + var token = this.context.strict ? options.stricted : options.firstRestricted; + this.throwUnexpectedToken(token, options.message); + } + return { + simple: options.simple, + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.parseAssignmentExpression = function () { + var expr; + if (!this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseYieldExpression(); + } + else { + var startToken = this.lookahead; + var token = startToken; + expr = this.parseConditionalExpression(); + if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { + if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { + var arg = this.parsePrimaryExpression(); + this.reinterpretExpressionAsPattern(arg); + expr = { + type: ArrowParameterPlaceHolder, + params: [arg], + async: true + }; + } + } + if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { + // https://tc39.github.io/ecma262/#sec-arrow-function-definitions + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var isAsync = expr.async; + var list = this.reinterpretAsCoverFormalsList(expr); + if (list) { + if (this.hasLineTerminator) { + this.tolerateUnexpectedToken(this.lookahead); + } + this.context.firstCoverInitializedNameError = null; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = list.simple; + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = true; + this.context.await = isAsync; + var node = this.startNode(startToken); + this.expect('=>'); + var body = void 0; + if (this.match('{')) { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + body = this.parseFunctionSourceElements(); + this.context.allowIn = previousAllowIn; + } + else { + body = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + var expression = body.type !== syntax_1.Syntax.BlockStatement; + if (this.context.strict && list.firstRestricted) { + this.throwUnexpectedToken(list.firstRestricted, list.message); + } + if (this.context.strict && list.stricted) { + this.tolerateUnexpectedToken(list.stricted, list.message); + } + expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : + this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + } + } + else { + if (this.matchAssign()) { + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { + var id = expr; + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); + } + if (this.scanner.isStrictModeReservedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + } + if (!this.match('=')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + this.reinterpretExpressionAsPattern(expr); + } + token = this.nextToken(); + var operator = token.value; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); + this.context.firstCoverInitializedNameError = null; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-comma-operator + Parser.prototype.parseExpression = function () { + var startToken = this.lookahead; + var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-block + Parser.prototype.parseStatementListItem = function () { + var statement; + this.context.isAssignmentTarget = true; + this.context.isBindingElement = true; + if (this.lookahead.type === 4 /* Keyword */) { + switch (this.lookahead.value) { + case 'export': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); + } + statement = this.parseExportDeclaration(); + break; + case 'import': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); + } + statement = this.parseImportDeclaration(); + break; + case 'const': + statement = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'class': + statement = this.parseClassDeclaration(); + break; + case 'let': + statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); + break; + default: + statement = this.parseStatement(); + break; + } + } + else { + statement = this.parseStatement(); + } + return statement; + }; + Parser.prototype.parseBlock = function () { + var node = this.createNode(); + this.expect('{'); + var block = []; + while (true) { + if (this.match('}')) { + break; + } + block.push(this.parseStatementListItem()); + } + this.expect('}'); + return this.finalize(node, new Node.BlockStatement(block)); + }; + // https://tc39.github.io/ecma262/#sec-let-and-const-declarations + Parser.prototype.parseLexicalBinding = function (kind, options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, kind); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (kind === 'const') { + if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else { + this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); + } + } + } + else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { + this.expect('='); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseBindingList = function (kind, options) { + var list = [this.parseLexicalBinding(kind, options)]; + while (this.match(',')) { + this.nextToken(); + list.push(this.parseLexicalBinding(kind, options)); + } + return list; + }; + Parser.prototype.isLexicalDeclaration = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + return (next.type === 3 /* Identifier */) || + (next.type === 7 /* Punctuator */ && next.value === '[') || + (next.type === 7 /* Punctuator */ && next.value === '{') || + (next.type === 4 /* Keyword */ && next.value === 'let') || + (next.type === 4 /* Keyword */ && next.value === 'yield'); + }; + Parser.prototype.parseLexicalDeclaration = function (options) { + var node = this.createNode(); + var kind = this.nextToken().value; + assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + var declarations = this.parseBindingList(kind, options); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); + }; + // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns + Parser.prototype.parseBindingRestElement = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params, kind); + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseArrayPattern = function (params, kind) { + var node = this.createNode(); + this.expect('['); + var elements = []; + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else { + if (this.match('...')) { + elements.push(this.parseBindingRestElement(params, kind)); + break; + } + else { + elements.push(this.parsePatternWithDefault(params, kind)); + } + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayPattern(elements)); + }; + Parser.prototype.parsePropertyPattern = function (params, kind) { + var node = this.createNode(); + var computed = false; + var shorthand = false; + var method = false; + var key; + var value; + if (this.lookahead.type === 3 /* Identifier */) { + var keyToken = this.lookahead; + key = this.parseVariableIdentifier(); + var init = this.finalize(node, new Node.Identifier(keyToken.value)); + if (this.match('=')) { + params.push(keyToken); + shorthand = true; + this.nextToken(); + var expr = this.parseAssignmentExpression(); + value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); + } + else if (!this.match(':')) { + params.push(keyToken); + shorthand = true; + value = init; + } + else { + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectPattern = function (params, kind) { + var node = this.createNode(); + var properties = []; + this.expect('{'); + while (!this.match('}')) { + properties.push(this.parsePropertyPattern(params, kind)); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectPattern(properties)); + }; + Parser.prototype.parsePattern = function (params, kind) { + var pattern; + if (this.match('[')) { + pattern = this.parseArrayPattern(params, kind); + } + else if (this.match('{')) { + pattern = this.parseObjectPattern(params, kind); + } + else { + if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); + } + params.push(this.lookahead); + pattern = this.parseVariableIdentifier(kind); + } + return pattern; + }; + Parser.prototype.parsePatternWithDefault = function (params, kind) { + var startToken = this.lookahead; + var pattern = this.parsePattern(params, kind); + if (this.match('=')) { + this.nextToken(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowYield = previousAllowYield; + pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); + } + return pattern; + }; + // https://tc39.github.io/ecma262/#sec-variable-statement + Parser.prototype.parseVariableIdentifier = function (kind) { + var node = this.createNode(); + var token = this.nextToken(); + if (token.type === 4 /* Keyword */ && token.value === 'yield') { + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else if (!this.context.allowYield) { + this.throwUnexpectedToken(token); + } + } + else if (token.type !== 3 /* Identifier */) { + if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else { + if (this.context.strict || token.value !== 'let' || kind !== 'var') { + this.throwUnexpectedToken(token); + } + } + } + else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { + this.tolerateUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseVariableDeclaration = function (options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, 'var'); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { + this.expect('='); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseVariableDeclarationList = function (options) { + var opt = { inFor: options.inFor }; + var list = []; + list.push(this.parseVariableDeclaration(opt)); + while (this.match(',')) { + this.nextToken(); + list.push(this.parseVariableDeclaration(opt)); + } + return list; + }; + Parser.prototype.parseVariableStatement = function () { + var node = this.createNode(); + this.expectKeyword('var'); + var declarations = this.parseVariableDeclarationList({ inFor: false }); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); + }; + // https://tc39.github.io/ecma262/#sec-empty-statement + Parser.prototype.parseEmptyStatement = function () { + var node = this.createNode(); + this.expect(';'); + return this.finalize(node, new Node.EmptyStatement()); + }; + // https://tc39.github.io/ecma262/#sec-expression-statement + Parser.prototype.parseExpressionStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ExpressionStatement(expr)); + }; + // https://tc39.github.io/ecma262/#sec-if-statement + Parser.prototype.parseIfClause = function () { + if (this.context.strict && this.matchKeyword('function')) { + this.tolerateError(messages_1.Messages.StrictFunction); + } + return this.parseStatement(); + }; + Parser.prototype.parseIfStatement = function () { + var node = this.createNode(); + var consequent; + var alternate = null; + this.expectKeyword('if'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + consequent = this.parseIfClause(); + if (this.matchKeyword('else')) { + this.nextToken(); + alternate = this.parseIfClause(); + } + } + return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); + }; + // https://tc39.github.io/ecma262/#sec-do-while-statement + Parser.prototype.parseDoWhileStatement = function () { + var node = this.createNode(); + this.expectKeyword('do'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + var body = this.parseStatement(); + this.context.inIteration = previousInIteration; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + } + else { + this.expect(')'); + if (this.match(';')) { + this.nextToken(); + } + } + return this.finalize(node, new Node.DoWhileStatement(body, test)); + }; + // https://tc39.github.io/ecma262/#sec-while-statement + Parser.prototype.parseWhileStatement = function () { + var node = this.createNode(); + var body; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.parseStatement(); + this.context.inIteration = previousInIteration; + } + return this.finalize(node, new Node.WhileStatement(test, body)); + }; + // https://tc39.github.io/ecma262/#sec-for-statement + // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements + Parser.prototype.parseForStatement = function () { + var init = null; + var test = null; + var update = null; + var forIn = true; + var left, right; + var node = this.createNode(); + this.expectKeyword('for'); + this.expect('('); + if (this.match(';')) { + this.nextToken(); + } + else { + if (this.matchKeyword('var')) { + init = this.createNode(); + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseVariableDeclarationList({ inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && this.matchKeyword('in')) { + var decl = declarations[0]; + if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { + this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); + } + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.expect(';'); + } + } + else if (this.matchKeyword('const') || this.matchKeyword('let')) { + init = this.createNode(); + var kind = this.nextToken().value; + if (!this.context.strict && this.lookahead.value === 'in') { + init = this.finalize(init, new Node.Identifier(kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseBindingList(kind, { inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + this.consumeSemicolon(); + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + } + } + } + else { + var initStartToken = this.lookahead; + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + init = this.inheritCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + if (this.matchKeyword('in')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForIn); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseExpression(); + init = null; + } + else if (this.matchContextualKeyword('of')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + if (this.match(',')) { + var initSeq = [init]; + while (this.match(',')) { + this.nextToken(); + initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); + } + this.expect(';'); + } + } + } + if (typeof left === 'undefined') { + if (!this.match(';')) { + test = this.parseExpression(); + } + this.expect(';'); + if (!this.match(')')) { + update = this.parseExpression(); + } + } + var body; + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.isolateCoverGrammar(this.parseStatement); + this.context.inIteration = previousInIteration; + } + return (typeof left === 'undefined') ? + this.finalize(node, new Node.ForStatement(init, test, update, body)) : + forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : + this.finalize(node, new Node.ForOfStatement(left, right, body)); + }; + // https://tc39.github.io/ecma262/#sec-continue-statement + Parser.prototype.parseContinueStatement = function () { + var node = this.createNode(); + this.expectKeyword('continue'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + label = id; + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration) { + this.throwError(messages_1.Messages.IllegalContinue); + } + return this.finalize(node, new Node.ContinueStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-break-statement + Parser.prototype.parseBreakStatement = function () { + var node = this.createNode(); + this.expectKeyword('break'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + label = id; + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration && !this.context.inSwitch) { + this.throwError(messages_1.Messages.IllegalBreak); + } + return this.finalize(node, new Node.BreakStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-return-statement + Parser.prototype.parseReturnStatement = function () { + if (!this.context.inFunctionBody) { + this.tolerateError(messages_1.Messages.IllegalReturn); + } + var node = this.createNode(); + this.expectKeyword('return'); + var hasArgument = !this.match(';') && !this.match('}') && + !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */; + var argument = hasArgument ? this.parseExpression() : null; + this.consumeSemicolon(); + return this.finalize(node, new Node.ReturnStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-with-statement + Parser.prototype.parseWithStatement = function () { + if (this.context.strict) { + this.tolerateError(messages_1.Messages.StrictModeWith); + } + var node = this.createNode(); + var body; + this.expectKeyword('with'); + this.expect('('); + var object = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + body = this.parseStatement(); + } + return this.finalize(node, new Node.WithStatement(object, body)); + }; + // https://tc39.github.io/ecma262/#sec-switch-statement + Parser.prototype.parseSwitchCase = function () { + var node = this.createNode(); + var test; + if (this.matchKeyword('default')) { + this.nextToken(); + test = null; + } + else { + this.expectKeyword('case'); + test = this.parseExpression(); + } + this.expect(':'); + var consequent = []; + while (true) { + if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { + break; + } + consequent.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.SwitchCase(test, consequent)); + }; + Parser.prototype.parseSwitchStatement = function () { + var node = this.createNode(); + this.expectKeyword('switch'); + this.expect('('); + var discriminant = this.parseExpression(); + this.expect(')'); + var previousInSwitch = this.context.inSwitch; + this.context.inSwitch = true; + var cases = []; + var defaultFound = false; + this.expect('{'); + while (true) { + if (this.match('}')) { + break; + } + var clause = this.parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + this.expect('}'); + this.context.inSwitch = previousInSwitch; + return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); + }; + // https://tc39.github.io/ecma262/#sec-labelled-statements + Parser.prototype.parseLabelledStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + var statement; + if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { + this.nextToken(); + var id = expr; + var key = '$' + id.name; + if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); + } + this.context.labelSet[key] = true; + var body = void 0; + if (this.matchKeyword('class')) { + this.tolerateUnexpectedToken(this.lookahead); + body = this.parseClassDeclaration(); + } + else if (this.matchKeyword('function')) { + var token = this.lookahead; + var declaration = this.parseFunctionDeclaration(); + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); + } + else if (declaration.generator) { + this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); + } + body = declaration; + } + else { + body = this.parseStatement(); + } + delete this.context.labelSet[key]; + statement = new Node.LabeledStatement(id, body); + } + else { + this.consumeSemicolon(); + statement = new Node.ExpressionStatement(expr); + } + return this.finalize(node, statement); + }; + // https://tc39.github.io/ecma262/#sec-throw-statement + Parser.prototype.parseThrowStatement = function () { + var node = this.createNode(); + this.expectKeyword('throw'); + if (this.hasLineTerminator) { + this.throwError(messages_1.Messages.NewlineAfterThrow); + } + var argument = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ThrowStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-try-statement + Parser.prototype.parseCatchClause = function () { + var node = this.createNode(); + this.expectKeyword('catch'); + this.expect('('); + if (this.match(')')) { + this.throwUnexpectedToken(this.lookahead); + } + var params = []; + var param = this.parsePattern(params); + var paramMap = {}; + for (var i = 0; i < params.length; i++) { + var key = '$' + params[i].value; + if (Object.prototype.hasOwnProperty.call(paramMap, key)) { + this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); + } + paramMap[key] = true; + } + if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(param.name)) { + this.tolerateError(messages_1.Messages.StrictCatchVariable); + } + } + this.expect(')'); + var body = this.parseBlock(); + return this.finalize(node, new Node.CatchClause(param, body)); + }; + Parser.prototype.parseFinallyClause = function () { + this.expectKeyword('finally'); + return this.parseBlock(); + }; + Parser.prototype.parseTryStatement = function () { + var node = this.createNode(); + this.expectKeyword('try'); + var block = this.parseBlock(); + var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; + var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; + if (!handler && !finalizer) { + this.throwError(messages_1.Messages.NoCatchOrFinally); + } + return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); + }; + // https://tc39.github.io/ecma262/#sec-debugger-statement + Parser.prototype.parseDebuggerStatement = function () { + var node = this.createNode(); + this.expectKeyword('debugger'); + this.consumeSemicolon(); + return this.finalize(node, new Node.DebuggerStatement()); + }; + // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations + Parser.prototype.parseStatement = function () { + var statement; + switch (this.lookahead.type) { + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* Template */: + case 9 /* RegularExpression */: + statement = this.parseExpressionStatement(); + break; + case 7 /* Punctuator */: + var value = this.lookahead.value; + if (value === '{') { + statement = this.parseBlock(); + } + else if (value === '(') { + statement = this.parseExpressionStatement(); + } + else if (value === ';') { + statement = this.parseEmptyStatement(); + } + else { + statement = this.parseExpressionStatement(); + } + break; + case 3 /* Identifier */: + statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); + break; + case 4 /* Keyword */: + switch (this.lookahead.value) { + case 'break': + statement = this.parseBreakStatement(); + break; + case 'continue': + statement = this.parseContinueStatement(); + break; + case 'debugger': + statement = this.parseDebuggerStatement(); + break; + case 'do': + statement = this.parseDoWhileStatement(); + break; + case 'for': + statement = this.parseForStatement(); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'if': + statement = this.parseIfStatement(); + break; + case 'return': + statement = this.parseReturnStatement(); + break; + case 'switch': + statement = this.parseSwitchStatement(); + break; + case 'throw': + statement = this.parseThrowStatement(); + break; + case 'try': + statement = this.parseTryStatement(); + break; + case 'var': + statement = this.parseVariableStatement(); + break; + case 'while': + statement = this.parseWhileStatement(); + break; + case 'with': + statement = this.parseWithStatement(); + break; + default: + statement = this.parseExpressionStatement(); + break; + } + break; + default: + statement = this.throwUnexpectedToken(this.lookahead); + } + return statement; + }; + // https://tc39.github.io/ecma262/#sec-function-definitions + Parser.prototype.parseFunctionSourceElements = function () { + var node = this.createNode(); + this.expect('{'); + var body = this.parseDirectivePrologues(); + var previousLabelSet = this.context.labelSet; + var previousInIteration = this.context.inIteration; + var previousInSwitch = this.context.inSwitch; + var previousInFunctionBody = this.context.inFunctionBody; + this.context.labelSet = {}; + this.context.inIteration = false; + this.context.inSwitch = false; + this.context.inFunctionBody = true; + while (this.lookahead.type !== 2 /* EOF */) { + if (this.match('}')) { + break; + } + body.push(this.parseStatementListItem()); + } + this.expect('}'); + this.context.labelSet = previousLabelSet; + this.context.inIteration = previousInIteration; + this.context.inSwitch = previousInSwitch; + this.context.inFunctionBody = previousInFunctionBody; + return this.finalize(node, new Node.BlockStatement(body)); + }; + Parser.prototype.validateParam = function (options, param, name) { + var key = '$' + name; + if (this.context.strict) { + if (this.scanner.isRestrictedWord(name)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + else if (!options.firstRestricted) { + if (this.scanner.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictParamName; + } + else if (this.scanner.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictReservedWord; + } + else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + /* istanbul ignore next */ + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); + } + else { + options.paramSet[key] = true; + } + }; + Parser.prototype.parseRestElement = function (params) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestParameter); + } + if (!this.match(')')) { + this.throwError(messages_1.Messages.ParameterAfterRestParameter); + } + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseFormalParameter = function (options) { + var params = []; + var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); + for (var i = 0; i < params.length; i++) { + this.validateParam(options, params[i], params[i].value); + } + options.simple = options.simple && (param instanceof Node.Identifier); + options.params.push(param); + }; + Parser.prototype.parseFormalParameters = function (firstRestricted) { + var options; + options = { + simple: true, + params: [], + firstRestricted: firstRestricted + }; + this.expect('('); + if (!this.match(')')) { + options.paramSet = {}; + while (this.lookahead.type !== 2 /* EOF */) { + this.parseFormalParameter(options); + if (this.match(')')) { + break; + } + this.expect(','); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return { + simple: options.simple, + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.matchAsyncFunction = function () { + var match = this.matchContextualKeyword('async'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); + } + return match; + }; + Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted = null; + if (!identifierIsOptional || !this.match('(')) { + var token = this.lookahead; + id = this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : + this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); + }; + Parser.prototype.parseFunctionExpression = function () { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted; + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + if (!this.match('(')) { + var token = this.lookahead; + id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : + this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive + Parser.prototype.parseDirective = function () { + var token = this.lookahead; + var node = this.createNode(); + var expr = this.parseExpression(); + var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; + this.consumeSemicolon(); + return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); + }; + Parser.prototype.parseDirectivePrologues = function () { + var firstRestricted = null; + var body = []; + while (true) { + var token = this.lookahead; + if (token.type !== 8 /* StringLiteral */) { + break; + } + var statement = this.parseDirective(); + body.push(statement); + var directive = statement.directive; + if (typeof directive !== 'string') { + break; + } + if (directive === 'use strict') { + this.context.strict = true; + if (firstRestricted) { + this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); + } + if (!this.context.allowStrictDirective) { + this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); + } + } + else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + return body; + }; + // https://tc39.github.io/ecma262/#sec-method-definitions + Parser.prototype.qualifiedPropertyName = function (token) { + switch (token.type) { + case 3 /* Identifier */: + case 8 /* StringLiteral */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 4 /* Keyword */: + return true; + case 7 /* Punctuator */: + return token.value === '['; + default: + break; + } + return false; + }; + Parser.prototype.parseGetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length > 0) { + this.tolerateError(messages_1.Messages.BadGetterArity); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseSetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length !== 1) { + this.tolerateError(messages_1.Messages.BadSetterArity); + } + else if (formalParameters.params[0] instanceof Node.RestElement) { + this.tolerateError(messages_1.Messages.BadSetterRestParameter); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseGeneratorMethod = function () { + var node = this.createNode(); + var isGenerator = true; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + this.context.allowYield = false; + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-generator-function-definitions + Parser.prototype.isStartOfExpression = function () { + var start = true; + var value = this.lookahead.value; + switch (this.lookahead.type) { + case 7 /* Punctuator */: + start = (value === '[') || (value === '(') || (value === '{') || + (value === '+') || (value === '-') || + (value === '!') || (value === '~') || + (value === '++') || (value === '--') || + (value === '/') || (value === '/='); // regular expression literal + break; + case 4 /* Keyword */: + start = (value === 'class') || (value === 'delete') || + (value === 'function') || (value === 'let') || (value === 'new') || + (value === 'super') || (value === 'this') || (value === 'typeof') || + (value === 'void') || (value === 'yield'); + break; + default: + break; + } + return start; + }; + Parser.prototype.parseYieldExpression = function () { + var node = this.createNode(); + this.expectKeyword('yield'); + var argument = null; + var delegate = false; + if (!this.hasLineTerminator) { + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + delegate = this.match('*'); + if (delegate) { + this.nextToken(); + argument = this.parseAssignmentExpression(); + } + else if (this.isStartOfExpression()) { + argument = this.parseAssignmentExpression(); + } + this.context.allowYield = previousAllowYield; + } + return this.finalize(node, new Node.YieldExpression(argument, delegate)); + }; + // https://tc39.github.io/ecma262/#sec-class-definitions + Parser.prototype.parseClassElement = function (hasConstructor) { + var token = this.lookahead; + var node = this.createNode(); + var kind = ''; + var key = null; + var value = null; + var computed = false; + var method = false; + var isStatic = false; + var isAsync = false; + if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + var id = key; + if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { + token = this.lookahead; + isStatic = true; + computed = this.match('['); + if (this.match('*')) { + this.nextToken(); + } + else { + key = this.parseObjectPropertyKey(); + } + } + if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + key = this.parseObjectPropertyKey(); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' || token.value === 'set') { + this.tolerateUnexpectedToken(token); + } + else if (token.value === 'constructor') { + this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); + } + } + } + } + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + if (!kind && key && this.match('(')) { + kind = 'init'; + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + if (!kind) { + this.throwUnexpectedToken(this.lookahead); + } + if (kind === 'init') { + kind = 'method'; + } + if (!computed) { + if (isStatic && this.isPropertyKey(key, 'prototype')) { + this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); + } + if (!isStatic && this.isPropertyKey(key, 'constructor')) { + if (kind !== 'method' || !method || (value && value.generator)) { + this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); + } + if (hasConstructor.value) { + this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); + } + else { + hasConstructor.value = true; + } + kind = 'constructor'; + } + } + return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); + }; + Parser.prototype.parseClassElementList = function () { + var body = []; + var hasConstructor = { value: false }; + this.expect('{'); + while (!this.match('}')) { + if (this.match(';')) { + this.nextToken(); + } + else { + body.push(this.parseClassElement(hasConstructor)); + } + } + this.expect('}'); + return body; + }; + Parser.prototype.parseClassBody = function () { + var node = this.createNode(); + var elementList = this.parseClassElementList(); + return this.finalize(node, new Node.ClassBody(elementList)); + }; + Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); + }; + Parser.prototype.parseClassExpression = function () { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); + }; + // https://tc39.github.io/ecma262/#sec-scripts + // https://tc39.github.io/ecma262/#sec-modules + Parser.prototype.parseModule = function () { + this.context.strict = true; + this.context.isModule = true; + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Module(body)); + }; + Parser.prototype.parseScript = function () { + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Script(body)); + }; + // https://tc39.github.io/ecma262/#sec-imports + Parser.prototype.parseModuleSpecifier = function () { + var node = this.createNode(); + if (this.lookahead.type !== 8 /* StringLiteral */) { + this.throwError(messages_1.Messages.InvalidModuleSpecifier); + } + var token = this.nextToken(); + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + // import {<foo as bar>} ...; + Parser.prototype.parseImportSpecifier = function () { + var node = this.createNode(); + var imported; + var local; + if (this.lookahead.type === 3 /* Identifier */) { + imported = this.parseVariableIdentifier(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + } + else { + imported = this.parseIdentifierName(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.ImportSpecifier(local, imported)); + }; + // {foo, bar as bas} + Parser.prototype.parseNamedImports = function () { + this.expect('{'); + var specifiers = []; + while (!this.match('}')) { + specifiers.push(this.parseImportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return specifiers; + }; + // import <foo> ...; + Parser.prototype.parseImportDefaultSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportDefaultSpecifier(local)); + }; + // import <* as foo> ...; + Parser.prototype.parseImportNamespaceSpecifier = function () { + var node = this.createNode(); + this.expect('*'); + if (!this.matchContextualKeyword('as')) { + this.throwError(messages_1.Messages.NoAsAfterImportNamespace); + } + this.nextToken(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); + }; + Parser.prototype.parseImportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalImportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('import'); + var src; + var specifiers = []; + if (this.lookahead.type === 8 /* StringLiteral */) { + // import 'foo'; + src = this.parseModuleSpecifier(); + } + else { + if (this.match('{')) { + // import {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else if (this.match('*')) { + // import * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { + // import foo + specifiers.push(this.parseImportDefaultSpecifier()); + if (this.match(',')) { + this.nextToken(); + if (this.match('*')) { + // import foo, * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.match('{')) { + // import foo, {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + src = this.parseModuleSpecifier(); + } + this.consumeSemicolon(); + return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); + }; + // https://tc39.github.io/ecma262/#sec-exports + Parser.prototype.parseExportSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + var exported = local; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + exported = this.parseIdentifierName(); + } + return this.finalize(node, new Node.ExportSpecifier(local, exported)); + }; + Parser.prototype.parseExportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalExportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('export'); + var exportDeclaration; + if (this.matchKeyword('default')) { + // export default ... + this.nextToken(); + if (this.matchKeyword('function')) { + // export default function foo () {} + // export default function () {} + var declaration = this.parseFunctionDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchKeyword('class')) { + // export default class foo {} + var declaration = this.parseClassDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchContextualKeyword('async')) { + // export default async function f () {} + // export default async function () {} + // export default async x => x + var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else { + if (this.matchContextualKeyword('from')) { + this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); + } + // export default {}; + // export default []; + // export default (1 + 2); + var declaration = this.match('{') ? this.parseObjectInitializer() : + this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + } + else if (this.match('*')) { + // export * from 'foo'; + this.nextToken(); + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + var src = this.parseModuleSpecifier(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); + } + else if (this.lookahead.type === 4 /* Keyword */) { + // export var f = 1; + var declaration = void 0; + switch (this.lookahead.value) { + case 'let': + case 'const': + declaration = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'var': + case 'class': + case 'function': + declaration = this.parseStatementListItem(); + break; + default: + this.throwUnexpectedToken(this.lookahead); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else if (this.matchAsyncFunction()) { + var declaration = this.parseFunctionDeclaration(); + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else { + var specifiers = []; + var source = null; + var isExportFromIdentifier = false; + this.expect('{'); + while (!this.match('}')) { + isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); + specifiers.push(this.parseExportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + if (this.matchContextualKeyword('from')) { + // export {default} from 'foo'; + // export {foo} from 'foo'; + this.nextToken(); + source = this.parseModuleSpecifier(); + this.consumeSemicolon(); + } + else if (isExportFromIdentifier) { + // export {default}; // missing fromClause + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + else { + // export {foo}; + this.consumeSemicolon(); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); + } + return exportDeclaration; + }; + return Parser; + }()); + exports.Parser = Parser; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + Object.defineProperty(exports, "__esModule", { value: true }); + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + exports.assert = assert; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + /* tslint:disable:max-classes-per-file */ + Object.defineProperty(exports, "__esModule", { value: true }); + var ErrorHandler = (function () { + function ErrorHandler() { + this.errors = []; + this.tolerant = false; + } + ErrorHandler.prototype.recordError = function (error) { + this.errors.push(error); + }; + ErrorHandler.prototype.tolerate = function (error) { + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + ErrorHandler.prototype.constructError = function (msg, column) { + var error = new Error(msg); + try { + throw error; + } + catch (base) { + /* istanbul ignore else */ + if (Object.create && Object.defineProperty) { + error = Object.create(base); + Object.defineProperty(error, 'column', { value: column }); + } + } + /* istanbul ignore next */ + return error; + }; + ErrorHandler.prototype.createError = function (index, line, col, description) { + var msg = 'Line ' + line + ': ' + description; + var error = this.constructError(msg, col); + error.index = index; + error.lineNumber = line; + error.description = description; + return error; + }; + ErrorHandler.prototype.throwError = function (index, line, col, description) { + throw this.createError(index, line, col, description); + }; + ErrorHandler.prototype.tolerateError = function (index, line, col, description) { + var error = this.createError(index, line, col, description); + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + return ErrorHandler; + }()); + exports.ErrorHandler = ErrorHandler; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // Error messages should be identical to V8. + exports.Messages = { + BadGetterArity: 'Getter must not have any formal parameters', + BadSetterArity: 'Setter must have exactly one formal parameter', + BadSetterRestParameter: 'Setter function argument must not be a rest parameter', + ConstructorIsAsync: 'Class constructor may not be an async method', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DeclarationMissingInitializer: 'Missing initializer in %0 declaration', + DefaultRestParameter: 'Unexpected token =', + DuplicateBinding: 'Duplicate binding %0', + DuplicateConstructor: 'A class may only have one constructor', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', + GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', + IllegalBreak: 'Illegal break statement', + IllegalContinue: 'Illegal continue statement', + IllegalExportDeclaration: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', + IllegalReturn: 'Illegal return statement', + InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', + InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', + InvalidModuleSpecifier: 'Unexpected token', + InvalidRegExp: 'Invalid regular expression', + LetInLexicalBinding: 'let is disallowed as a lexically bound name', + MissingFromClause: 'Unexpected token', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NewlineAfterThrow: 'Illegal newline after throw', + NoAsAfterImportNamespace: 'Unexpected token', + NoCatchOrFinally: 'Missing catch or finally after try', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + Redeclaration: '%0 \'%1\' has already been declared', + StaticPrototype: 'Classes may not have static property named prototype', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + UnexpectedEOS: 'Unexpected end of input', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedNumber: 'Unexpected number', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedString: 'Unexpected string', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedToken: 'Unexpected token %0', + UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', + UnknownLabel: 'Undefined label \'%0\'', + UnterminatedRegExp: 'Invalid regular expression: missing /' + }; + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var character_1 = __webpack_require__(4); + var messages_1 = __webpack_require__(11); + function hexValue(ch) { + return '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + function octalValue(ch) { + return '01234567'.indexOf(ch); + } + var Scanner = (function () { + function Scanner(code, handler) { + this.source = code; + this.errorHandler = handler; + this.trackComment = false; + this.length = code.length; + this.index = 0; + this.lineNumber = (code.length > 0) ? 1 : 0; + this.lineStart = 0; + this.curlyStack = []; + } + Scanner.prototype.saveState = function () { + return { + index: this.index, + lineNumber: this.lineNumber, + lineStart: this.lineStart + }; + }; + Scanner.prototype.restoreState = function (state) { + this.index = state.index; + this.lineNumber = state.lineNumber; + this.lineStart = state.lineStart; + }; + Scanner.prototype.eof = function () { + return this.index >= this.length; + }; + Scanner.prototype.throwUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + Scanner.prototype.tolerateUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + // https://tc39.github.io/ecma262/#sec-comments + Scanner.prototype.skipSingleLineComment = function (offset) { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - offset; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - offset + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + ++this.index; + if (character_1.Character.isLineTerminator(ch)) { + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart - 1 + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index - 1], + range: [start, this.index - 1], + loc: loc + }; + comments.push(entry); + } + if (ch === 13 && this.source.charCodeAt(this.index) === 10) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + return comments; + } + } + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + }; + Scanner.prototype.skipMultiLineComment = function () { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - 2; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - 2 + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isLineTerminator(ch)) { + if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + ++this.index; + this.lineStart = this.index; + } + else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (this.source.charCodeAt(this.index + 1) === 0x2F) { + this.index += 2; + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index - 2], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + } + ++this.index; + } + else { + ++this.index; + } + } + // Ran off the end of the file - the whole thing is a comment + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + this.tolerateUnexpectedToken(); + return comments; + }; + Scanner.prototype.scanComments = function () { + var comments; + if (this.trackComment) { + comments = []; + } + var start = (this.index === 0); + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isWhiteSpace(ch)) { + ++this.index; + } + else if (character_1.Character.isLineTerminator(ch)) { + ++this.index; + if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + start = true; + } + else if (ch === 0x2F) { + ch = this.source.charCodeAt(this.index + 1); + if (ch === 0x2F) { + this.index += 2; + var comment = this.skipSingleLineComment(2); + if (this.trackComment) { + comments = comments.concat(comment); + } + start = true; + } + else if (ch === 0x2A) { + this.index += 2; + var comment = this.skipMultiLineComment(); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (start && ch === 0x2D) { + // U+003E is '>' + if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { + // '-->' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // `<!--` + var comment = this.skipSingleLineComment(4); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else { + break; + } + } + return comments; + }; + // https://tc39.github.io/ecma262/#sec-future-reserved-words + Scanner.prototype.isFutureReservedWord = function (id) { + switch (id) { + case 'enum': + case 'export': + case 'import': + case 'super': + return true; + default: + return false; + } + }; + Scanner.prototype.isStrictModeReservedWord = function (id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + }; + Scanner.prototype.isRestrictedWord = function (id) { + return id === 'eval' || id === 'arguments'; + }; + // https://tc39.github.io/ecma262/#sec-keywords + Scanner.prototype.isKeyword = function (id) { + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + }; + Scanner.prototype.codePointAt = function (i) { + var cp = this.source.charCodeAt(i); + if (cp >= 0xD800 && cp <= 0xDBFF) { + var second = this.source.charCodeAt(i + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + var first = cp; + cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return cp; + }; + Scanner.prototype.scanHexEscape = function (prefix) { + var len = (prefix === 'u') ? 4 : 2; + var code = 0; + for (var i = 0; i < len; ++i) { + if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { + code = code * 16 + hexValue(this.source[this.index++]); + } + else { + return null; + } + } + return String.fromCharCode(code); + }; + Scanner.prototype.scanUnicodeCodePointEscape = function () { + var ch = this.source[this.index]; + var code = 0; + // At least, one hex digit is required. + if (ch === '}') { + this.throwUnexpectedToken(); + } + while (!this.eof()) { + ch = this.source[this.index++]; + if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) { + break; + } + code = code * 16 + hexValue(ch); + } + if (code > 0x10FFFF || ch !== '}') { + this.throwUnexpectedToken(); + } + return character_1.Character.fromCodePoint(code); + }; + Scanner.prototype.getIdentifier = function () { + var start = this.index++; + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + this.index = start; + return this.getComplexIdentifier(); + } + else if (ch >= 0xD800 && ch < 0xDFFF) { + // Need to handle surrogate pairs. + this.index = start; + return this.getComplexIdentifier(); + } + if (character_1.Character.isIdentifierPart(ch)) { + ++this.index; + } + else { + break; + } + } + return this.source.slice(start, this.index); + }; + Scanner.prototype.getComplexIdentifier = function () { + var cp = this.codePointAt(this.index); + var id = character_1.Character.fromCodePoint(cp); + this.index += id.length; + // '\u' (U+005C, U+0075) denotes an escaped character. + var ch; + if (cp === 0x5C) { + if (this.source.charCodeAt(this.index) !== 0x75) { + this.throwUnexpectedToken(); + } + ++this.index; + if (this.source[this.index] === '{') { + ++this.index; + ch = this.scanUnicodeCodePointEscape(); + } + else { + ch = this.scanHexEscape('u'); + if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) { + this.throwUnexpectedToken(); + } + } + id = ch; + } + while (!this.eof()) { + cp = this.codePointAt(this.index); + if (!character_1.Character.isIdentifierPart(cp)) { + break; + } + ch = character_1.Character.fromCodePoint(cp); + id += ch; + this.index += ch.length; + // '\u' (U+005C, U+0075) denotes an escaped character. + if (cp === 0x5C) { + id = id.substr(0, id.length - 1); + if (this.source.charCodeAt(this.index) !== 0x75) { + this.throwUnexpectedToken(); + } + ++this.index; + if (this.source[this.index] === '{') { + ++this.index; + ch = this.scanUnicodeCodePointEscape(); + } + else { + ch = this.scanHexEscape('u'); + if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { + this.throwUnexpectedToken(); + } + } + id += ch; + } + } + return id; + }; + Scanner.prototype.octalToDecimal = function (ch) { + // \0 is not octal escape sequence + var octal = (ch !== '0'); + var code = octalValue(ch); + if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + octal = true; + code = code * 8 + octalValue(this.source[this.index++]); + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + code = code * 8 + octalValue(this.source[this.index++]); + } + } + return { + code: code, + octal: octal + }; + }; + // https://tc39.github.io/ecma262/#sec-names-and-keywords + Scanner.prototype.scanIdentifier = function () { + var type; + var start = this.index; + // Backslash (U+005C) starts an escaped character. + var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier(); + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = 3 /* Identifier */; + } + else if (this.isKeyword(id)) { + type = 4 /* Keyword */; + } + else if (id === 'null') { + type = 5 /* NullLiteral */; + } + else if (id === 'true' || id === 'false') { + type = 1 /* BooleanLiteral */; + } + else { + type = 3 /* Identifier */; + } + if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) { + var restore = this.index; + this.index = start; + this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord); + this.index = restore; + } + return { + type: type, + value: id, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-punctuators + Scanner.prototype.scanPunctuator = function () { + var start = this.index; + // Check for most common single-character punctuators. + var str = this.source[this.index]; + switch (str) { + case '(': + case '{': + if (str === '{') { + this.curlyStack.push('{'); + } + ++this.index; + break; + case '.': + ++this.index; + if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') { + // Spread operator: ... + this.index += 2; + str = '...'; + } + break; + case '}': + ++this.index; + this.curlyStack.pop(); + break; + case ')': + case ';': + case ',': + case '[': + case ']': + case ':': + case '?': + case '~': + ++this.index; + break; + default: + // 4-character punctuator. + str = this.source.substr(this.index, 4); + if (str === '>>>=') { + this.index += 4; + } + else { + // 3-character punctuators. + str = str.substr(0, 3); + if (str === '===' || str === '!==' || str === '>>>' || + str === '<<=' || str === '>>=' || str === '**=') { + this.index += 3; + } + else { + // 2-character punctuators. + str = str.substr(0, 2); + if (str === '&&' || str === '||' || str === '==' || str === '!=' || + str === '+=' || str === '-=' || str === '*=' || str === '/=' || + str === '++' || str === '--' || str === '<<' || str === '>>' || + str === '&=' || str === '|=' || str === '^=' || str === '%=' || + str === '<=' || str === '>=' || str === '=>' || str === '**') { + this.index += 2; + } + else { + // 1-character punctuators. + str = this.source[this.index]; + if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { + ++this.index; + } + } + } + } + } + if (this.index === start) { + this.throwUnexpectedToken(); + } + return { + type: 7 /* Punctuator */, + value: str, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + Scanner.prototype.scanHexLiteral = function (start) { + var num = ''; + while (!this.eof()) { + if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { + break; + } + num += this.source[this.index++]; + } + if (num.length === 0) { + this.throwUnexpectedToken(); + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseInt('0x' + num, 16), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.scanBinaryLiteral = function (start) { + var num = ''; + var ch; + while (!this.eof()) { + ch = this.source[this.index]; + if (ch !== '0' && ch !== '1') { + break; + } + num += this.source[this.index++]; + } + if (num.length === 0) { + // only 0b or 0B + this.throwUnexpectedToken(); + } + if (!this.eof()) { + ch = this.source.charCodeAt(this.index); + /* istanbul ignore else */ + if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) { + this.throwUnexpectedToken(); + } + } + return { + type: 6 /* NumericLiteral */, + value: parseInt(num, 2), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.scanOctalLiteral = function (prefix, start) { + var num = ''; + var octal = false; + if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) { + octal = true; + num = '0' + this.source[this.index++]; + } + else { + ++this.index; + } + while (!this.eof()) { + if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + break; + } + num += this.source[this.index++]; + } + if (!octal && num.length === 0) { + // only 0o or 0O + this.throwUnexpectedToken(); + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseInt(num, 8), + octal: octal, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.isImplicitOctalLiteral = function () { + // Implicit octal, unless there is a non-octal digit. + // (Annex B.1.1 on Numeric Literals) + for (var i = this.index + 1; i < this.length; ++i) { + var ch = this.source[i]; + if (ch === '8' || ch === '9') { + return false; + } + if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + return true; + } + } + return true; + }; + Scanner.prototype.scanNumericLiteral = function () { + var start = this.index; + var ch = this.source[start]; + assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); + var num = ''; + if (ch !== '.') { + num = this.source[this.index++]; + ch = this.source[this.index]; + // Hex number starts with '0x'. + // Octal number starts with '0'. + // Octal number in ES6 starts with '0o'. + // Binary number in ES6 starts with '0b'. + if (num === '0') { + if (ch === 'x' || ch === 'X') { + ++this.index; + return this.scanHexLiteral(start); + } + if (ch === 'b' || ch === 'B') { + ++this.index; + return this.scanBinaryLiteral(start); + } + if (ch === 'o' || ch === 'O') { + return this.scanOctalLiteral(ch, start); + } + if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + if (this.isImplicitOctalLiteral()) { + return this.scanOctalLiteral(ch, start); + } + } + } + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + ch = this.source[this.index]; + } + if (ch === '.') { + num += this.source[this.index++]; + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + ch = this.source[this.index]; + } + if (ch === 'e' || ch === 'E') { + num += this.source[this.index++]; + ch = this.source[this.index]; + if (ch === '+' || ch === '-') { + num += this.source[this.index++]; + } + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + } + else { + this.throwUnexpectedToken(); + } + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseFloat(num), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-string-literals + Scanner.prototype.scanStringLiteral = function () { + var start = this.index; + var quote = this.source[start]; + assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); + ++this.index; + var octal = false; + var str = ''; + while (!this.eof()) { + var ch = this.source[this.index++]; + if (ch === quote) { + quote = ''; + break; + } + else if (ch === '\\') { + ch = this.source[this.index++]; + if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'u': + if (this.source[this.index] === '{') { + ++this.index; + str += this.scanUnicodeCodePointEscape(); + } + else { + var unescaped_1 = this.scanHexEscape(ch); + if (unescaped_1 === null) { + this.throwUnexpectedToken(); + } + str += unescaped_1; + } + break; + case 'x': + var unescaped = this.scanHexEscape(ch); + if (unescaped === null) { + this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); + } + str += unescaped; + break; + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\x0B'; + break; + case '8': + case '9': + str += ch; + this.tolerateUnexpectedToken(); + break; + default: + if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + var octToDec = this.octalToDecimal(ch); + octal = octToDec.octal || octal; + str += String.fromCharCode(octToDec.code); + } + else { + str += ch; + } + break; + } + } + else { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + } + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + break; + } + else { + str += ch; + } + } + if (quote !== '') { + this.index = start; + this.throwUnexpectedToken(); + } + return { + type: 8 /* StringLiteral */, + value: str, + octal: octal, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components + Scanner.prototype.scanTemplate = function () { + var cooked = ''; + var terminated = false; + var start = this.index; + var head = (this.source[start] === '`'); + var tail = false; + var rawOffset = 2; + ++this.index; + while (!this.eof()) { + var ch = this.source[this.index++]; + if (ch === '`') { + rawOffset = 1; + tail = true; + terminated = true; + break; + } + else if (ch === '$') { + if (this.source[this.index] === '{') { + this.curlyStack.push('${'); + ++this.index; + terminated = true; + break; + } + cooked += ch; + } + else if (ch === '\\') { + ch = this.source[this.index++]; + if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + cooked += '\n'; + break; + case 'r': + cooked += '\r'; + break; + case 't': + cooked += '\t'; + break; + case 'u': + if (this.source[this.index] === '{') { + ++this.index; + cooked += this.scanUnicodeCodePointEscape(); + } + else { + var restore = this.index; + var unescaped_2 = this.scanHexEscape(ch); + if (unescaped_2 !== null) { + cooked += unescaped_2; + } + else { + this.index = restore; + cooked += ch; + } + } + break; + case 'x': + var unescaped = this.scanHexEscape(ch); + if (unescaped === null) { + this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); + } + cooked += unescaped; + break; + case 'b': + cooked += '\b'; + break; + case 'f': + cooked += '\f'; + break; + case 'v': + cooked += '\v'; + break; + default: + if (ch === '0') { + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + // Illegal: \01 \02 and so on + this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); + } + cooked += '\0'; + } + else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + // Illegal: \1 \2 + this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); + } + else { + cooked += ch; + } + break; + } + } + else { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + } + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + cooked += '\n'; + } + else { + cooked += ch; + } + } + if (!terminated) { + this.throwUnexpectedToken(); + } + if (!head) { + this.curlyStack.pop(); + } + return { + type: 10 /* Template */, + value: this.source.slice(start + 1, this.index - rawOffset), + cooked: cooked, + head: head, + tail: tail, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals + Scanner.prototype.testRegExp = function (pattern, flags) { + // The BMP character to use as a replacement for astral symbols when + // translating an ES6 "u"-flagged pattern to an ES5-compatible + // approximation. + // Note: replacing with '\uFFFF' enables false positives in unlikely + // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid + // pattern that would not be detected by this substitution. + var astralSubstitute = '\uFFFF'; + var tmp = pattern; + var self = this; + if (flags.indexOf('u') >= 0) { + tmp = tmp + .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) { + var codePoint = parseInt($1 || $2, 16); + if (codePoint > 0x10FFFF) { + self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); + } + if (codePoint <= 0xFFFF) { + return String.fromCharCode(codePoint); + } + return astralSubstitute; + }) + .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute); + } + // First, detect invalid regular expressions. + try { + RegExp(tmp); + } + catch (e) { + this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); + } + // Return a regular expression object for this pattern-flag pair, or + // `null` in case the current environment doesn't support the flags it + // uses. + try { + return new RegExp(pattern, flags); + } + catch (exception) { + /* istanbul ignore next */ + return null; + } + }; + Scanner.prototype.scanRegExpBody = function () { + var ch = this.source[this.index]; + assert_1.assert(ch === '/', 'Regular expression literal must start with a slash'); + var str = this.source[this.index++]; + var classMarker = false; + var terminated = false; + while (!this.eof()) { + ch = this.source[this.index++]; + str += ch; + if (ch === '\\') { + ch = this.source[this.index++]; + // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + str += ch; + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + else if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } + else { + if (ch === '/') { + terminated = true; + break; + } + else if (ch === '[') { + classMarker = true; + } + } + } + if (!terminated) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + // Exclude leading and trailing slash. + return str.substr(1, str.length - 2); + }; + Scanner.prototype.scanRegExpFlags = function () { + var str = ''; + var flags = ''; + while (!this.eof()) { + var ch = this.source[this.index]; + if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { + break; + } + ++this.index; + if (ch === '\\' && !this.eof()) { + ch = this.source[this.index]; + if (ch === 'u') { + ++this.index; + var restore = this.index; + var char = this.scanHexEscape('u'); + if (char !== null) { + flags += char; + for (str += '\\u'; restore < this.index; ++restore) { + str += this.source[restore]; + } + } + else { + this.index = restore; + flags += 'u'; + str += '\\u'; + } + this.tolerateUnexpectedToken(); + } + else { + str += '\\'; + this.tolerateUnexpectedToken(); + } + } + else { + flags += ch; + str += ch; + } + } + return flags; + }; + Scanner.prototype.scanRegExp = function () { + var start = this.index; + var pattern = this.scanRegExpBody(); + var flags = this.scanRegExpFlags(); + var value = this.testRegExp(pattern, flags); + return { + type: 9 /* RegularExpression */, + value: '', + pattern: pattern, + flags: flags, + regex: value, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.lex = function () { + if (this.eof()) { + return { + type: 2 /* EOF */, + value: '', + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: this.index, + end: this.index + }; + } + var cp = this.source.charCodeAt(this.index); + if (character_1.Character.isIdentifierStart(cp)) { + return this.scanIdentifier(); + } + // Very common: ( and ) and ; + if (cp === 0x28 || cp === 0x29 || cp === 0x3B) { + return this.scanPunctuator(); + } + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (cp === 0x27 || cp === 0x22) { + return this.scanStringLiteral(); + } + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (cp === 0x2E) { + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) { + return this.scanNumericLiteral(); + } + return this.scanPunctuator(); + } + if (character_1.Character.isDecimalDigit(cp)) { + return this.scanNumericLiteral(); + } + // Template literals start with ` (U+0060) for template head + // or } (U+007D) for template middle or template tail. + if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) { + return this.scanTemplate(); + } + // Possible identifier start in a surrogate pair. + if (cp >= 0xD800 && cp < 0xDFFF) { + if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) { + return this.scanIdentifier(); + } + } + return this.scanPunctuator(); + }; + return Scanner; + }()); + exports.Scanner = Scanner; + + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TokenName = {}; + exports.TokenName[1 /* BooleanLiteral */] = 'Boolean'; + exports.TokenName[2 /* EOF */] = '<end>'; + exports.TokenName[3 /* Identifier */] = 'Identifier'; + exports.TokenName[4 /* Keyword */] = 'Keyword'; + exports.TokenName[5 /* NullLiteral */] = 'Null'; + exports.TokenName[6 /* NumericLiteral */] = 'Numeric'; + exports.TokenName[7 /* Punctuator */] = 'Punctuator'; + exports.TokenName[8 /* StringLiteral */] = 'String'; + exports.TokenName[9 /* RegularExpression */] = 'RegularExpression'; + exports.TokenName[10 /* Template */] = 'Template'; + + +/***/ }, +/* 14 */ +/***/ function(module, exports) { + + "use strict"; + // Generated by generate-xhtml-entities.js. DO NOT MODIFY! + Object.defineProperty(exports, "__esModule", { value: true }); + exports.XHTMLEntities = { + quot: '\u0022', + amp: '\u0026', + apos: '\u0027', + gt: '\u003E', + nbsp: '\u00A0', + iexcl: '\u00A1', + cent: '\u00A2', + pound: '\u00A3', + curren: '\u00A4', + yen: '\u00A5', + brvbar: '\u00A6', + sect: '\u00A7', + uml: '\u00A8', + copy: '\u00A9', + ordf: '\u00AA', + laquo: '\u00AB', + not: '\u00AC', + shy: '\u00AD', + reg: '\u00AE', + macr: '\u00AF', + deg: '\u00B0', + plusmn: '\u00B1', + sup2: '\u00B2', + sup3: '\u00B3', + acute: '\u00B4', + micro: '\u00B5', + para: '\u00B6', + middot: '\u00B7', + cedil: '\u00B8', + sup1: '\u00B9', + ordm: '\u00BA', + raquo: '\u00BB', + frac14: '\u00BC', + frac12: '\u00BD', + frac34: '\u00BE', + iquest: '\u00BF', + Agrave: '\u00C0', + Aacute: '\u00C1', + Acirc: '\u00C2', + Atilde: '\u00C3', + Auml: '\u00C4', + Aring: '\u00C5', + AElig: '\u00C6', + Ccedil: '\u00C7', + Egrave: '\u00C8', + Eacute: '\u00C9', + Ecirc: '\u00CA', + Euml: '\u00CB', + Igrave: '\u00CC', + Iacute: '\u00CD', + Icirc: '\u00CE', + Iuml: '\u00CF', + ETH: '\u00D0', + Ntilde: '\u00D1', + Ograve: '\u00D2', + Oacute: '\u00D3', + Ocirc: '\u00D4', + Otilde: '\u00D5', + Ouml: '\u00D6', + times: '\u00D7', + Oslash: '\u00D8', + Ugrave: '\u00D9', + Uacute: '\u00DA', + Ucirc: '\u00DB', + Uuml: '\u00DC', + Yacute: '\u00DD', + THORN: '\u00DE', + szlig: '\u00DF', + agrave: '\u00E0', + aacute: '\u00E1', + acirc: '\u00E2', + atilde: '\u00E3', + auml: '\u00E4', + aring: '\u00E5', + aelig: '\u00E6', + ccedil: '\u00E7', + egrave: '\u00E8', + eacute: '\u00E9', + ecirc: '\u00EA', + euml: '\u00EB', + igrave: '\u00EC', + iacute: '\u00ED', + icirc: '\u00EE', + iuml: '\u00EF', + eth: '\u00F0', + ntilde: '\u00F1', + ograve: '\u00F2', + oacute: '\u00F3', + ocirc: '\u00F4', + otilde: '\u00F5', + ouml: '\u00F6', + divide: '\u00F7', + oslash: '\u00F8', + ugrave: '\u00F9', + uacute: '\u00FA', + ucirc: '\u00FB', + uuml: '\u00FC', + yacute: '\u00FD', + thorn: '\u00FE', + yuml: '\u00FF', + OElig: '\u0152', + oelig: '\u0153', + Scaron: '\u0160', + scaron: '\u0161', + Yuml: '\u0178', + fnof: '\u0192', + circ: '\u02C6', + tilde: '\u02DC', + Alpha: '\u0391', + Beta: '\u0392', + Gamma: '\u0393', + Delta: '\u0394', + Epsilon: '\u0395', + Zeta: '\u0396', + Eta: '\u0397', + Theta: '\u0398', + Iota: '\u0399', + Kappa: '\u039A', + Lambda: '\u039B', + Mu: '\u039C', + Nu: '\u039D', + Xi: '\u039E', + Omicron: '\u039F', + Pi: '\u03A0', + Rho: '\u03A1', + Sigma: '\u03A3', + Tau: '\u03A4', + Upsilon: '\u03A5', + Phi: '\u03A6', + Chi: '\u03A7', + Psi: '\u03A8', + Omega: '\u03A9', + alpha: '\u03B1', + beta: '\u03B2', + gamma: '\u03B3', + delta: '\u03B4', + epsilon: '\u03B5', + zeta: '\u03B6', + eta: '\u03B7', + theta: '\u03B8', + iota: '\u03B9', + kappa: '\u03BA', + lambda: '\u03BB', + mu: '\u03BC', + nu: '\u03BD', + xi: '\u03BE', + omicron: '\u03BF', + pi: '\u03C0', + rho: '\u03C1', + sigmaf: '\u03C2', + sigma: '\u03C3', + tau: '\u03C4', + upsilon: '\u03C5', + phi: '\u03C6', + chi: '\u03C7', + psi: '\u03C8', + omega: '\u03C9', + thetasym: '\u03D1', + upsih: '\u03D2', + piv: '\u03D6', + ensp: '\u2002', + emsp: '\u2003', + thinsp: '\u2009', + zwnj: '\u200C', + zwj: '\u200D', + lrm: '\u200E', + rlm: '\u200F', + ndash: '\u2013', + mdash: '\u2014', + lsquo: '\u2018', + rsquo: '\u2019', + sbquo: '\u201A', + ldquo: '\u201C', + rdquo: '\u201D', + bdquo: '\u201E', + dagger: '\u2020', + Dagger: '\u2021', + bull: '\u2022', + hellip: '\u2026', + permil: '\u2030', + prime: '\u2032', + Prime: '\u2033', + lsaquo: '\u2039', + rsaquo: '\u203A', + oline: '\u203E', + frasl: '\u2044', + euro: '\u20AC', + image: '\u2111', + weierp: '\u2118', + real: '\u211C', + trade: '\u2122', + alefsym: '\u2135', + larr: '\u2190', + uarr: '\u2191', + rarr: '\u2192', + darr: '\u2193', + harr: '\u2194', + crarr: '\u21B5', + lArr: '\u21D0', + uArr: '\u21D1', + rArr: '\u21D2', + dArr: '\u21D3', + hArr: '\u21D4', + forall: '\u2200', + part: '\u2202', + exist: '\u2203', + empty: '\u2205', + nabla: '\u2207', + isin: '\u2208', + notin: '\u2209', + ni: '\u220B', + prod: '\u220F', + sum: '\u2211', + minus: '\u2212', + lowast: '\u2217', + radic: '\u221A', + prop: '\u221D', + infin: '\u221E', + ang: '\u2220', + and: '\u2227', + or: '\u2228', + cap: '\u2229', + cup: '\u222A', + int: '\u222B', + there4: '\u2234', + sim: '\u223C', + cong: '\u2245', + asymp: '\u2248', + ne: '\u2260', + equiv: '\u2261', + le: '\u2264', + ge: '\u2265', + sub: '\u2282', + sup: '\u2283', + nsub: '\u2284', + sube: '\u2286', + supe: '\u2287', + oplus: '\u2295', + otimes: '\u2297', + perp: '\u22A5', + sdot: '\u22C5', + lceil: '\u2308', + rceil: '\u2309', + lfloor: '\u230A', + rfloor: '\u230B', + loz: '\u25CA', + spades: '\u2660', + clubs: '\u2663', + hearts: '\u2665', + diams: '\u2666', + lang: '\u27E8', + rang: '\u27E9' + }; + + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var error_handler_1 = __webpack_require__(10); + var scanner_1 = __webpack_require__(12); + var token_1 = __webpack_require__(13); + var Reader = (function () { + function Reader() { + this.values = []; + this.curly = this.paren = -1; + } + // A function following one of those tokens is an expression. + Reader.prototype.beforeFunctionExpression = function (t) { + return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0; + }; + // Determine if forward slash (/) is an operator or part of a regular expression + // https://github.com/mozilla/sweet.js/wiki/design + Reader.prototype.isRegexStart = function () { + var previous = this.values[this.values.length - 1]; + var regex = (previous !== null); + switch (previous) { + case 'this': + case ']': + regex = false; + break; + case ')': + var keyword = this.values[this.paren - 1]; + regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with'); + break; + case '}': + // Dividing a function by anything makes little sense, + // but we have to check for that. + regex = false; + if (this.values[this.curly - 3] === 'function') { + // Anonymous function, e.g. function(){} /42 + var check = this.values[this.curly - 4]; + regex = check ? !this.beforeFunctionExpression(check) : false; + } + else if (this.values[this.curly - 4] === 'function') { + // Named function, e.g. function f(){} /42/ + var check = this.values[this.curly - 5]; + regex = check ? !this.beforeFunctionExpression(check) : true; + } + break; + default: + break; + } + return regex; + }; + Reader.prototype.push = function (token) { + if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) { + if (token.value === '{') { + this.curly = this.values.length; + } + else if (token.value === '(') { + this.paren = this.values.length; + } + this.values.push(token.value); + } + else { + this.values.push(null); + } + }; + return Reader; + }()); + var Tokenizer = (function () { + function Tokenizer(code, config) { + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false; + this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false; + this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false; + this.buffer = []; + this.reader = new Reader(); + } + Tokenizer.prototype.errors = function () { + return this.errorHandler.errors; + }; + Tokenizer.prototype.getNextToken = function () { + if (this.buffer.length === 0) { + var comments = this.scanner.scanComments(); + if (this.scanner.trackComment) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var value = this.scanner.source.slice(e.slice[0], e.slice[1]); + var comment = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: value + }; + if (this.trackRange) { + comment.range = e.range; + } + if (this.trackLoc) { + comment.loc = e.loc; + } + this.buffer.push(comment); + } + } + if (!this.scanner.eof()) { + var loc = void 0; + if (this.trackLoc) { + loc = { + start: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }, + end: {} + }; + } + var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart(); + var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex(); + this.reader.push(token); + var entry = { + type: token_1.TokenName[token.type], + value: this.scanner.source.slice(token.start, token.end) + }; + if (this.trackRange) { + entry.range = [token.start, token.end]; + } + if (this.trackLoc) { + loc.end = { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + entry.loc = loc; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + entry.regex = { pattern: pattern, flags: flags }; + } + this.buffer.push(entry); + } + } + return this.buffer.shift(); + }; + return Tokenizer; + }()); + exports.Tokenizer = Tokenizer; + + +/***/ } +/******/ ]) +}); +; +/*global define, Reflect */ + +/* + * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac), + * and the recursive nature of esprima can cause it to overflow pretty + * quickly. So favor it built in Reflect parser: + * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API + */ +define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) { + if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') { + return Reflect; + } else { + return esprima; + } +}); +(function webpackUniversalModuleDefinition(root, factory) { +var exports, module; + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define('source-map', [], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(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__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 Google 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '<dir>/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = util.toSetString(aStr); + var isDuplicate = has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[sStr] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ } +/******/ ]) +}); +;//Distributed under the BSD license: +//Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> +define('uglifyjs', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) { + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function array_to_hash(a) { + var ret = Object.create(null); + for (var i = 0; i < a.length; ++i) + ret[a[i]] = true; + return ret; +}; + +function slice(a, start) { + return Array.prototype.slice.call(a, start || 0); +}; + +function characters(str) { + return str.split(""); +}; + +function member(name, array) { + return array.indexOf(name) >= 0; +}; + +function find_if(func, array) { + for (var i = 0, n = array.length; i < n; ++i) { + if (func(array[i])) + return array[i]; + } +}; + +function repeat_string(str, i) { + if (i <= 0) return ""; + if (i == 1) return str; + var d = repeat_string(str, i >> 1); + d += d; + if (i & 1) d += str; + return d; +}; + +function configure_error_stack(fn) { + Object.defineProperty(fn.prototype, "stack", { + get: function() { + var err = new Error(this.message); + err.name = this.name; + try { + throw err; + } catch(e) { + return e.stack; + } + } + }); +} + +function DefaultsError(msg, defs) { + this.message = msg; + this.defs = defs; +}; +DefaultsError.prototype = Object.create(Error.prototype); +DefaultsError.prototype.constructor = DefaultsError; +DefaultsError.prototype.name = "DefaultsError"; +configure_error_stack(DefaultsError); + +DefaultsError.croak = function(msg, defs) { + throw new DefaultsError(msg, defs); +}; + +function defaults(args, defs, croak) { + if (args === true) + args = {}; + var ret = args || {}; + if (croak) for (var i in ret) if (HOP(ret, i) && !HOP(defs, i)) + DefaultsError.croak("`" + i + "` is not a supported option", defs); + for (var i in defs) if (HOP(defs, i)) { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + return ret; +}; + +function merge(obj, ext) { + var count = 0; + for (var i in ext) if (HOP(ext, i)) { + obj[i] = ext[i]; + count++; + } + return count; +}; + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function(){ + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } + else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + }; + if (a instanceof Array) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } + else { + for (i in a) if (HOP(a, i)) if (doit()) break; + } + return top.concat(ret); + }; + MAP.at_top = function(val) { return new AtTop(val) }; + MAP.splice = function(val) { return new Splice(val) }; + MAP.last = function(val) { return new Last(val) }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val }; + function Splice(val) { this.v = val }; + function Last(val) { this.v = val }; + return MAP; +})(); + +function push_uniq(array, el) { + if (array.indexOf(el) < 0) + array.push(el); +}; + +function string_template(text, props) { + return text.replace(/\{(.+?)\}/g, function(str, p){ + return props && props[p]; + }); +}; + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +}; + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + }; + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + }; + return _ms(array); +}; + +function set_difference(a, b) { + return a.filter(function(el){ + return b.indexOf(el) < 0; + }); +}; + +function set_intersection(a, b) { + return a.filter(function(el){ + return b.indexOf(el) >= 0; + }); +}; + +// this function is taken from Acorn [1], written by Marijn Haverbeke +// [1] https://github.com/marijnh/acorn +function makePredicate(words) { + if (!(words instanceof Array)) words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function quote(word) { + return JSON.stringify(word).replace(/[\u2028\u2029]/g, function(s) { + switch (s) { + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + } + return s; + }); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + quote(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + quote(arr[i]) + ":"; + f += "return true}return false;"; + } + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + // Otherwise, simply generate a flat `switch` statement. + } else { + compareTo(words); + } + return new Function("str", f); +}; + +function all(array, predicate) { + for (var i = array.length; --i >= 0;) + if (!predicate(array[i])) + return false; + return true; +}; + +function Dictionary() { + this._values = Object.create(null); + this._size = 0; +}; +Dictionary.prototype = { + set: function(key, val) { + if (!this.has(key)) ++this._size; + this._values["$" + key] = val; + return this; + }, + add: function(key, val) { + if (this.has(key)) { + this.get(key).push(val); + } else { + this.set(key, [ val ]); + } + return this; + }, + get: function(key) { return this._values["$" + key] }, + del: function(key) { + if (this.has(key)) { + --this._size; + delete this._values["$" + key]; + } + return this; + }, + has: function(key) { return ("$" + key) in this._values }, + each: function(f) { + for (var i in this._values) + f(this._values[i], i.substr(1)); + }, + size: function() { + return this._size; + }, + map: function(f) { + var ret = []; + for (var i in this._values) + ret.push(f(this._values[i], i.substr(1))); + return ret; + }, + toObject: function() { return this._values } +}; +Dictionary.fromObject = function(obj) { + var dict = new Dictionary(); + dict._size = merge(dict._values, obj); + return dict; +}; + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + var node = stack.parent(-1); + for (var i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Seq && p.car === node ) || + (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) || + (p instanceof AST_Dot && p.expression === node ) || + (p instanceof AST_Sub && p.expression === node ) || + (p instanceof AST_Conditional && p.condition === node ) || + (p instanceof AST_Binary && p.left === node ) || + (p instanceof AST_UnaryPostfix && p.expression === node )) + { + node = p; + } else { + return false; + } + } +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function DEFNODE(type, props, methods, base) { + if (arguments.length < 4) base = AST_Node; + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + var proto = base && new base; + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (HOP(methods, i)) { + if (/^\$/.test(i)) { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + if (typeof exports !== "undefined") { + exports["AST_" + type] = ctor; + } + return ctor; +}; + +var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", { +}, null); + +var AST_Node = DEFNODE("Node", "start end", { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + } +}, null); + +AST_Node.warn_function = null; +AST_Node.warn = function(txt, props) { + if (AST_Node.warn_function) + AST_Node.warn_function(string_template(txt, props)); +}; + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value scope quote", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + scope: "[AST_Scope/S] The scope that this directive affects", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +function walk_body(node, visitor) { + var body = node.body; + if (body instanceof AST_Statement) { + body._walk(visitor); + } + else for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +}; + +var AST_Block = DEFNODE("Block", "body", { + $documentation: "A body of statements (usually bracketed)", + $propdoc: { + body: "[AST_Statement*] an array of statements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + }); + } +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)", + _walk: function(visitor) { + return visitor._visit(this); + } +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", null, { + $documentation: "Internal class. All loops inherit from it." +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + this.condition._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init name object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + directives: "[string*/S] an array of directives declared in this scope", + variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + functions: "[Object/S] like `variables`, but only lists function declarations", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_enclose: function(arg_parameter_pairs) { + var self = this; + var args = []; + var parameters = []; + + arg_parameter_pairs.forEach(function(pair) { + var splitAt = pair.lastIndexOf(":"); + + args.push(pair.substr(0, splitAt)); + parameters.push(pair.substr(splitAt + 1)); + }); + + var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(self.body); + } + })); + return wrapped_tl; + }, + wrap_commonjs: function(name, export_all) { + var self = this; + var to_export = []; + if (export_all) { + self.figure_out_scope(); + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_SymbolDeclaration && node.definition().global) { + if (!find_if(function(n){ return n.name == node.name }, to_export)) + to_export.push(node); + } + })); + } + var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive) { + switch (node.value) { + case "$ORIG": + return MAP.splice(self.body); + case "$EXPORTS": + var body = []; + to_export.forEach(function(sym){ + body.push(new AST_SimpleStatement({ + body: new AST_Assign({ + left: new AST_Sub({ + expression: new AST_SymbolRef({ name: "exports" }), + property: new AST_String({ value: sym.name }), + }), + operator: "=", + right: new AST_SymbolRef(sym), + }), + })); + }); + return MAP.splice(body); + } + } + })); + return wrapped_tl; + } +}, AST_Scope); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg*] array of function arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps†(for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits†(`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function(){ + this.value._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function(){ + this.label._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminantâ€" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + } +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.argname._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + } +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + } +}); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + }); + } +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Seq = DEFNODE("Seq", "car cdr", { + $documentation: "A sequence expression (two comma-separated expressions)", + $propdoc: { + car: "[AST_Node] first element in sequence", + cdr: "[AST_Node] second element in sequence" + }, + $cons: function(x, y) { + var seq = new AST_Seq(x); + seq.car = x; + seq.cdr = y; + return seq; + }, + $from_array: function(array) { + if (array.length == 0) return null; + if (array.length == 1) return array[0].clone(); + var list = null; + for (var i = array.length; --i >= 0;) { + list = AST_Seq.cons(array[i], list); + } + var p = list; + while (p) { + if (p.cdr && !p.cdr.cdr) { + p.cdr = p.cdr.car; + break; + } + p = p.cdr; + } + return list; + }, + to_array: function() { + var p = this, a = []; + while (p) { + a.push(p.car); + if (p.cdr && !(p.cdr instanceof AST_Seq)) { + a.push(p.cdr); + break; + } + p = p.cdr; + } + return a; + }, + add: function(node) { + var p = this; + while (p) { + if (!(p.cdr instanceof AST_Seq)) { + var cell = AST_Seq.cons(p.cdr, node); + return p.cdr = cell; + } + p = p.cdr; + } + }, + len: function() { + if (this.cdr instanceof AST_Seq) { + return this.cdr.len() + 1; + } else { + return 2; + } + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.car._walk(visitor); + if (this.cdr) this.cdr._walk(visitor); + }); + } +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container†expression", + property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" + } +}); + +var AST_Dot = DEFNODE("Dot", null, { + $documentation: "A dotted property access expression", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.property._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "left operator right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.left._walk(visitor); + this.right._walk(visitor); + }); + } +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + } +}); + +var AST_Assign = DEFNODE("Assign", null, { + $documentation: "An assignment expression — `a = b + 5`", +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + } +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + } +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an AST_SymbolAccessor.", + value: "[AST_Node] property value. For setters and getters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.value._walk(visitor); + }); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { + $documentation: "An object setter property", +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { + $documentation: "An object getter property", +}, AST_ObjectProperty); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols", +}); + +var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { + $documentation: "The name of a property accessor (setter/getter function)" +}, AST_Symbol); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolDeclaration); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value literal", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + literal: "[string] numeric value as string (optional)" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp" + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function(){}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function(){}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ TreeWalker ]----- */ + +function TreeWalker(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); +}; +TreeWalker.prototype = { + _visit: function(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function(){ + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(node); + return ret; + }, + parent: function(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + }, + push: function (node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } + this.stack.push(node); + }, + pop: function(node) { + this.stack.pop(); + if (node instanceof AST_Lambda) { + this.directives = Object.getPrototypeOf(this.directives); + } + }, + self: function() { + return this.stack[this.stack.length - 1]; + }, + find_parent: function(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + }, + has_directive: function(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + }, + in_boolean_context: function() { + var stack = this.stack; + var i = stack.length, self = stack[--i]; + while (i > 0) { + var p = stack[--i]; + if ((p instanceof AST_If && p.condition === self) || + (p instanceof AST_Conditional && p.condition === self) || + (p instanceof AST_DWLoop && p.condition === self) || + (p instanceof AST_For && p.condition === self) || + (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) + { + return true; + } + if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) + return false; + self = p; + } + }, + loopcontrol_target: function(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with'; +var KEYWORDS_ATOM = 'false null true'; +var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield' + + " " + KEYWORDS_ATOM + " " + KEYWORDS; +var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")); + +var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = makePredicate(characters("gmsiy")); + +/* -----[ Tokenizer ]----- */ + +// regexps adapted from http://xregexp.com/plugins/#unicode +var UNICODE = { + letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), + digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"), + non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), + space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), + connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") +}; + +function is_letter(code) { + return (code >= 97 && code <= 122) + || (code >= 65 && code <= 90) + || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); +}; + +function is_digit(code) { + return code >= 48 && code <= 57; +}; + +function is_alphanumeric_char(code) { + return is_digit(code) || is_letter(code); +}; + +function is_unicode_digit(code) { + return UNICODE.digit.test(String.fromCharCode(code)); +} + +function is_unicode_combining_mark(ch) { + return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); +}; + +function is_unicode_connector_punctuation(ch) { + return UNICODE.connector_punctuation.test(ch); +}; + +function is_identifier(name) { + return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name); +}; + +function is_identifier_start(code) { + return code == 36 || code == 95 || is_letter(code); +}; + +function is_identifier_char(ch) { + var code = ch.charCodeAt(0); + return is_identifier_start(code) + || is_digit(code) + || code == 8204 // \u200c: zero-width non-joiner <ZWNJ> + || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c) + || is_unicode_combining_mark(ch) + || is_unicode_connector_punctuation(ch) + || is_unicode_digit(code) + ; +}; + +function is_identifier_string(str){ + return /^[a-z_$][a-z0-9_$]*$/i.test(str); +}; + +function parse_js_number(num) { + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +}; + +function JS_Parse_Error(message, filename, line, col, pos) { + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; +}; +JS_Parse_Error.prototype = Object.create(Error.prototype); +JS_Parse_Error.prototype.constructor = JS_Parse_Error; +JS_Parse_Error.prototype.name = "SyntaxError"; +configure_error_stack(JS_Parse_Error); + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +}; + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +}; + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [], + directives : {}, + directive_stack : [] + }; + + function peek() { return S.text.charAt(S.pos); }; + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS(ch)) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (!in_string && ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + ++S.col; + } + return ch; + }; + + function forward(i) { + while (i-- > 0) next(); + }; + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + }; + + function find_eol() { + var text = S.text; + for (var i = S.pos, n = S.text.length; i < n; ++i) { + var ch = text[i]; + if (NEWLINE_CHARS(ch)) + return i; + } + return -1; + }; + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + }; + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + }; + + var prev_was_dot = false; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION(value))); + if (type == "punc" && value == ".") { + prev_was_dot = true; + } else if (!is_comment) { + prev_was_dot = false; + } + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endline : S.line, + endcol : S.col, + endpos : S.pos, + nlb : S.newline_before, + file : filename + }; + if (/^(?:num|string|regexp)$/i.test(type)) { + ret.raw = $TEXT.substring(ret.pos, ret.endpos); + } + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return new AST_Token(ret); + }; + + function skip_whitespace() { + while (WHITESPACE_CHARS(peek())) + next(); + }; + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + }; + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + }; + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, i){ + var code = ch.charCodeAt(0); + switch (code) { + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + return is_alphanumeric_char(code); + }); + if (prefix) num = prefix + num; + if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) { + parse_error("Legacy octal literals are not allowed in strict mode"); + } + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + }; + + function read_escaped_char(in_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 120 : return String.fromCharCode(hex_bytes(2)); // \x + case 117 : return String.fromCharCode(hex_bytes(4)); // \u + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + if (ch >= "0" && ch <= "7") + return read_octal_escape_sequence(ch); + return ch; + }; + + function read_octal_escape_sequence(ch) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict")) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + function hex_bytes(n) { + var num = 0; + for (; n > 0; --n) { + var digit = parseInt(next(true), 16); + if (isNaN(digit)) + parse_error("Invalid hex-character pattern in string"); + num = (num << 4) | digit; + } + return num; + }; + + var read_string = with_eof_error("Unterminated string constant", function(quote_char){ + var quote = next(), ret = ""; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true); + else if (NEWLINE_CHARS(ch)) parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret += ch; + } + var tok = token("string", ret); + tok.quote = quote_char; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + }; + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, '\n'); + // update stream position + forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.regex_allowed = regex_allowed; + return next_token; + }); + + function read_name() { + var backslash = false, name = "", ch, escaped = false, hex; + while ((ch = peek()) != null) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } + else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (KEYWORDS(name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS(ch)) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + regexp += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + regexp += ch; + } else if (ch == "]" && in_class) { + in_class = false; + regexp += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + regexp += ch; + } + var mods = read_name(); + try { + return token("regexp", new RegExp(regexp, mods)); + } catch(e) { + parse_error(e.message); + } + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + }; + return token("operator", grow(prefix || next())); + }; + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + }; + + function handle_dot() { + next(); + return is_digit(peek().charCodeAt(0)) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM(word) ? token("atom", word) + : !KEYWORDS(word) ? token("name", word) + : OPERATORS(word) ? token("operator", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + }; + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("<!--")) { + forward(4); + skip_line_comment("comment3"); + continue; + } + if (looking_at("-->") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(ch); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS(ch)) return token("punc", next()); + if (OPERATOR_CHARS(ch)) return read_operator(); + if (code == 92 || is_identifier_start(code)) return read_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + }; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + } + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + } + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + } + + next_token.has_directive = function(directive) { + return S.directives[directive] !== undefined && + S.directives[directive] > 0; + } + + return next_token; + +}; + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var PRECEDENCE = (function(a, ret){ + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ], + {} +); + +var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); + +var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + + options = defaults(options, { + bare_returns : false, + cli : false, + expression : false, + filename : null, + html5_comments : true, + shebang : true, + strict : false, + toplevel : null, + }); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + }; + + function peek() { return S.peeked || (S.peeked = S.input()); }; + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + }; + + function token_error(token, msg) { + croak(msg, token.line, token.col); + }; + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + }; + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !options.strict && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + }; + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + }; + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser(); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + }; + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + }; + + var statement = embed_tokens(function() { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (S.token.raw.indexOf("\\") == -1 + && (token.nlb + || is_token(token, "eof") + || is_token(token, "punc", ";") + || is_token(token, "punc", "}"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir ? new AST_Directive(stat.body) : stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(statement) + }); + + case "for": + next(); + return for_(); + + case "function": + next(); + return function_(AST_Defun); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (find_if(function(l){ return l.name == label.name }, S.labels)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref){ + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + }; + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + }; + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = find_if(function(l){ return l.name == label.name }, S.labels); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } + else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + }; + + function for_() { + expect("("); + var init = null; + if (!is("punc", ";")) { + init = is("keyword", "var") + ? (next(), var_(true)) + : expression(true, true); + if (is("operator", "in")) { + if (init instanceof AST_Var && init.definitions.length > 1) + croak("Only one variable declaration allowed in for..in loop"); + next(); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(statement) + }); + }; + + function for_in(init) { + var lhs = init instanceof AST_Var ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + name : lhs, + object : obj, + body : in_loop(statement) + }); + }; + + var function_ = function(ctor) { + var in_statement = ctor === AST_Defun; + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) + unexpected(); + expect("("); + return new ctor({ + name: name, + argnames: (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + a.push(as_symbol(AST_SymbolFunarg)); + } + next(); + return a; + })(true, []), + body: (function(loop, labels){ + ++S.in_function; + S.in_directives = true; + S.input.push_directives_stack(); + S.in_loop = 0; + S.labels = []; + var a = block_(); + S.input.pop_directives_stack(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + return a; + })(S.in_loop, S.labels) + }); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } + else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + }; + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + expect("("); + var name = as_symbol(AST_SymbolCatch); + expect(")"); + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + }; + + function vardefs(no_in, in_const) { + var a = []; + for (;;) { + a.push(new AST_VarDef({ + start : S.token, + name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), + value : is("operator", "=") ? (next(), expression(false, no_in)) : null, + end : prev() + })); + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, false), + end : prev() + }); + }; + + var const_ = function() { + return new AST_Const({ + start : prev(), + definitions : vardefs(false, true), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }), allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + case "keyword": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + case "operator": + if (!is_identifier_string(tok.value)) { + croak("Invalid getter/setter name: " + tok.value, + tok.line, tok.col, tok.pos); + } + ret = _make_symbol(AST_SymbolRef); + break; + } + next(); + return ret; + }; + + var expr_atom = function(allow_calls) { + if (is("operator", "new")) { + return new_(allow_calls); + } + var start = S.token; + if (is("punc")) { + switch (start.value) { + case "(": + next(); + var ex = expression(true); + ex.start = start; + ex.end = S.token; + expect(")"); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (ATOMIC_START_TOKEN[S.token.type]) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens(function() { + return function_(AST_Accessor); + }); + + var object_ = embed_tokens(function() { + expect("{"); + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + var start = S.token; + var type = start.type; + var name = as_property_name(); + if (type == "name" && !is("punc", ":")) { + var key = new AST_SymbolAccessor({ + start: S.token, + name: as_property_name(), + end: prev() + }); + if (name == "get") { + a.push(new AST_ObjectGetter({ + start : start, + key : key, + value : create_accessor(), + end : prev() + })); + continue; + } + if (name == "set") { + a.push(new AST_ObjectSetter({ + start : start, + key : key, + value : create_accessor(), + end : prev() + })); + continue; + } + } + expect(":"); + a.push(new AST_ObjectKeyVal({ + start : start, + quote : start.quote, + key : name, + value : expression(false), + end : prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "operator": + if (!KEYWORDS(tmp.value)) unexpected(); + case "num": + case "string": + case "name": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(); + } + }; + + function as_name() { + var tmp = S.token; + if (tmp.type != "name") unexpected(); + next(); + return tmp.value; + }; + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : type)({ + name : String(name), + start : S.token, + end : S.token + }); + }; + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + next(); + return sym; + }; + + var subscripts = function(expr, allow_calls) { + var start = expr.start; + if (is("punc", ".")) { + next(); + return subscripts(new AST_Dot({ + start : start, + expression : expr, + property : as_name(), + end : prev() + }), allow_calls); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + property : prop, + end : prev() + }), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(new AST_Call({ + start : start, + expression : expr, + args : expr_list(")"), + end : prev() + }), true); + } + return expr; + }; + + var maybe_unary = function(allow_calls) { + var start = S.token; + if (is("operator") && UNARY_PREFIX(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls); + while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + return new ctor({ operator: op, expression: expr }); + }; + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && prec > min_prec) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + if (options.cli) return true; + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + }; + + var maybe_assign = function(no_in) { + var start = S.token; + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && ASSIGNMENT(val)) { + if (is_assignable(left)) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return new AST_Seq({ + start : start, + car : expr, + cdr : expression(true, no_in), + end : peek() + }); + } + return expr; + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + }; + + if (options.expression) { + return expression(true); + } + + return (function(){ + var start = S.token; + var body = []; + S.input.push_directives_stack(); + while (!is("eof")) + body.push(statement()); + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +// Tree transformer helpers. + +function TreeTransformer(before, after) { + TreeWalker.call(this); + this.before = before; + this.after = after; +} +TreeTransformer.prototype = new TreeWalker; + +(function(undefined){ + + function _(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list){ + var x, y; + tw.push(this); + if (tw.before) x = tw.before(this, descend, in_list); + if (x === undefined) { + if (!tw.after) { + x = this; + descend(x, tw); + } else { + tw.stack[tw.stack.length - 1] = x = this; + descend(x, tw); + y = tw.after(x, in_list); + if (y !== undefined) x = y; + } + } + tw.pop(this); + return x; + }); + }; + + function do_list(list, tw) { + return MAP(list, function(node){ + return node.transform(tw, true); + }); + }; + + _(AST_Node, noop); + + _(AST_LabeledStatement, function(self, tw){ + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_SimpleStatement, function(self, tw){ + self.body = self.body.transform(tw); + }); + + _(AST_Block, function(self, tw){ + self.body = do_list(self.body, tw); + }); + + _(AST_DWLoop, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_For, function(self, tw){ + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_ForIn, function(self, tw){ + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_With, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_Exit, function(self, tw){ + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_LoopControl, function(self, tw){ + if (self.label) self.label = self.label.transform(tw); + }); + + _(AST_If, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); + }); + + _(AST_Switch, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Case, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Try, function(self, tw){ + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); + }); + + _(AST_Catch, function(self, tw){ + self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Definitions, function(self, tw){ + self.definitions = do_list(self.definitions, tw); + }); + + _(AST_VarDef, function(self, tw){ + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_Lambda, function(self, tw){ + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Call, function(self, tw){ + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); + }); + + _(AST_Seq, function(self, tw){ + self.car = self.car.transform(tw); + self.cdr = self.cdr.transform(tw); + }); + + _(AST_Dot, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Sub, function(self, tw){ + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); + }); + + _(AST_Unary, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Binary, function(self, tw){ + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); + }); + + _(AST_Conditional, function(self, tw){ + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); + }); + + _(AST_Array, function(self, tw){ + self.elements = do_list(self.elements, tw); + }); + + _(AST_Object, function(self, tw){ + self.properties = do_list(self.properties, tw); + }); + + _(AST_ObjectProperty, function(self, tw){ + self.value = self.value.transform(tw); + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(scope, index, orig) { + this.name = orig.name; + this.orig = [ orig ]; + this.scope = scope; + this.references = []; + this.global = false; + this.mangled_name = null; + this.undeclared = false; + this.index = index; + this.id = SymbolDef.next_id++; +}; + +SymbolDef.next_id = 1; + +SymbolDef.prototype = { + unmangleable: function(options) { + if (!options) options = {}; + + return (this.global && !options.toplevel) + || this.undeclared + || (!options.eval && (this.scope.uses_eval || this.scope.uses_with)) + || (options.keep_fnames + && (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun)); + }, + mangle: function(options) { + var cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } + else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (!options.screw_ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + var def; + if (this.defun && (def = this.defun.variables.get(this.name))) { + this.mangled_name = def.mangled_name || def.name; + } else + this.mangled_name = s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +}; + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ + options = defaults(options, { + cache: null, + screw_ie8: true, + }); + + // pass 1: setup scope chaining and handle definitions + var self = this; + var scope = self.parent_scope = null; + var labels = new Dictionary(); + var defun = null; + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Catch) { + var save_scope = scope; + scope = new AST_Scope(node); + scope.init_scope_vars(save_scope); + descend(); + scope = save_scope; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Dictionary(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.del(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node); + } + else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + (node.scope = defun.parent_scope).def_function(node); + } + else if (node instanceof AST_SymbolVar + || node instanceof AST_SymbolConst) { + defun.def_variable(node); + if (defun !== scope) { + node.mark_enclosed(options); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(options); + } + } + } + else if (node instanceof AST_SymbolCatch) { + scope.def_variable(node).defun = defun; + } + else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + }); + self.walk(tw); + + // pass 2: find back references and eval + var func = null; + var globals = self.globals = new Dictionary(); + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Lambda) { + var prev_func = func; + func = node; + descend(); + func = prev_func; + return true; + } + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym = node.scope.find_variable(name); + if (node.scope instanceof AST_Lambda && name == "arguments") { + node.scope.uses_arguments = true; + } + if (!sym) { + sym = self.def_global(node); + } + node.thedef = sym; + node.reference(options); + return true; + } + }); + self.walk(tw); + + // pass 3: fix up any scoping issue with IE8 + if (!options.screw_ie8) { + self.walk(new TreeWalker(function(node, descend) { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.thedef.defun; + var def = scope.find_variable(name) || self.globals.get(name) || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(options); + }); + node.thedef = def; + return true; + } + })); + } + + if (options.cache) { + this.cname = options.cache.cname; + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node){ + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, globals.size(), node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope){ + this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Lambda.DEFMETHOD("init_scope_vars", function(){ + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolVar({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function(options) { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (options.keep_fnames) { + s.functions.each(function(d) { + push_uniq(def.scope.enclosed, d); + }); + } + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function(options) { + this.definition().references.push(this); + this.mark_enclosed(options); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name){ + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol){ + this.functions.set(symbol.name, this.def_variable(symbol)); +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol){ + var def; + if (!this.variables.has(symbol.name)) { + def = new SymbolDef(this, this.variables.size(), symbol); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } else { + def = this.variables.get(symbol.name); + def.orig.push(symbol); + } + return symbol.thedef = def; +}); + +AST_Scope.DEFMETHOD("next_mangled", function(options){ + var ext = this.enclosed; + out: while (true) { + var m = base54(++this.cname); + if (!is_identifier(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name excepted from mangling. + if (options.except.indexOf(m) >= 0) continue; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (var i = ext.length; --i >= 0;) { + var sym = ext[i]; + var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); + if (m == name) continue out; + } + return m; + } +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def){ + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = AST_Lambda.prototype.next_mangled.call(this, options, def); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options){ + return this.definition().unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("unreferenced", function(){ + return this.definition().references.length == 0 + && !(this.scope.uses_eval || this.scope.uses_with); +}); + +AST_Symbol.DEFMETHOD("undeclared", function(){ + return this.definition().undeclared; +}); + +AST_LabelRef.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Label.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("definition", function(){ + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function(){ + return this.definition().global; +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ + return defaults(options, { + eval : false, + except : [], + keep_fnames : false, + screw_ie8 : true, + sort : false, // Ignored. Flag retained for backwards compatibility. + toplevel : false, + }); +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options){ + options = this._default_mangler_options(options); + + // Never mangle arguments + options.except.push('arguments'); + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.cache) { + this.globals.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + to_mangle.push(symbol); + } + }); + } + + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Scope) { + var p = tw.parent(), a = []; + node.variables.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + a.push(symbol); + } + }); + to_mangle.push.apply(to_mangle, a); + return; + } + if (node instanceof AST_Label) { + var name; + do name = base54(++lname); while (!is_identifier(name)); + node.mangled_name = name; + return true; + } + if (options.screw_ie8 && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + this.walk(tw); + to_mangle.forEach(function(def){ def.mangle(options) }); + + if (options.cache) { + options.cache.cname = this.cname; + } +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ + options = this._default_mangler_options(options); + var tw = new TreeWalker(function(node){ + if (node instanceof AST_Constant) + base54.consider(node.print_to_string()); + else if (node instanceof AST_Return) + base54.consider("return"); + else if (node instanceof AST_Throw) + base54.consider("throw"); + else if (node instanceof AST_Continue) + base54.consider("continue"); + else if (node instanceof AST_Break) + base54.consider("break"); + else if (node instanceof AST_Debugger) + base54.consider("debugger"); + else if (node instanceof AST_Directive) + base54.consider(node.value); + else if (node instanceof AST_While) + base54.consider("while"); + else if (node instanceof AST_Do) + base54.consider("do while"); + else if (node instanceof AST_If) { + base54.consider("if"); + if (node.alternative) base54.consider("else"); + } + else if (node instanceof AST_Var) + base54.consider("var"); + else if (node instanceof AST_Const) + base54.consider("const"); + else if (node instanceof AST_Lambda) + base54.consider("function"); + else if (node instanceof AST_For) + base54.consider("for"); + else if (node instanceof AST_ForIn) + base54.consider("for in"); + else if (node instanceof AST_Switch) + base54.consider("switch"); + else if (node instanceof AST_Case) + base54.consider("case"); + else if (node instanceof AST_Default) + base54.consider("default"); + else if (node instanceof AST_With) + base54.consider("with"); + else if (node instanceof AST_ObjectSetter) + base54.consider("set" + node.key); + else if (node instanceof AST_ObjectGetter) + base54.consider("get" + node.key); + else if (node instanceof AST_ObjectKeyVal) + base54.consider(node.key); + else if (node instanceof AST_New) + base54.consider("new"); + else if (node instanceof AST_This) + base54.consider("this"); + else if (node instanceof AST_Try) + base54.consider("try"); + else if (node instanceof AST_Catch) + base54.consider("catch"); + else if (node instanceof AST_Finally) + base54.consider("finally"); + else if (node instanceof AST_Symbol && node.unmangleable(options)) + base54.consider(node.name); + else if (node instanceof AST_Unary || node instanceof AST_Binary) + base54.consider(node.operator); + else if (node instanceof AST_Dot) + base54.consider(node.property); + }); + this.walk(tw); + base54.sort(); +}); + +var base54 = (function() { + var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; + var chars, frequency; + function reset() { + frequency = Object.create(null); + chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); + chars.forEach(function(ch){ frequency[ch] = 0 }); + } + base54.consider = function(str){ + for (var i = str.length; --i >= 0;) { + var code = str.charCodeAt(i); + if (code in frequency) ++frequency[code]; + } + }; + base54.sort = function() { + chars = mergeSort(chars, function(a, b){ + if (is_digit(a) && !is_digit(b)) return 1; + if (is_digit(b) && !is_digit(a)) return -1; + return frequency[b] - frequency[a]; + }); + }; + base54.reset = reset; + reset(); + base54.get = function(){ return chars }; + base54.freq = function(){ return frequency }; + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += String.fromCharCode(chars[num % base]); + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + }; + return base54; +})(); + +AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ + options = defaults(options, { + assign_to_global : true, + eval : true, + func_arguments : true, + nested_defuns : true, + undeclared : false, // this makes a lot of noise + unreferenced : true, + }); + var tw = new TreeWalker(function(node){ + if (options.undeclared + && node instanceof AST_SymbolRef + && node.undeclared()) + { + // XXX: this also warns about JS standard names, + // i.e. Object, Array, parseInt etc. Should add a list of + // exceptions. + AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.assign_to_global) + { + var sym = null; + if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) + sym = node.left; + else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) + sym = node.init; + if (sym + && (sym.undeclared() + || (sym.global() && sym.scope !== sym.definition().scope))) { + AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { + msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", + name: sym.name, + file: sym.start.file, + line: sym.start.line, + col: sym.start.col + }); + } + } + if (options.eval + && node instanceof AST_SymbolRef + && node.undeclared() + && node.name == "eval") { + AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); + } + if (options.unreferenced + && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) + && !(node instanceof AST_SymbolCatch) + && node.unreferenced()) { + AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { + type: node instanceof AST_Label ? "Label" : "Symbol", + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.func_arguments + && node instanceof AST_Lambda + && node.uses_arguments) { + AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { + name: node.name ? node.name.name : "anonymous", + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.nested_defuns + && node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope)) { + AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { + name: node.name.name, + type: tw.parent().TYPE, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + }); + this.walk(tw); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; + +function is_some_comments(comment) { + // multiline comment + return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value); +} + +function OutputStream(options) { + + options = defaults(options, { + ascii_only : false, + beautify : false, + bracketize : false, + comments : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_quoted_props: false, + max_line_len : false, + preamble : null, + preserve_line : false, + quote_keys : false, + quote_style : 0, + screw_ie8 : true, + semicolons : true, + shebang : true, + source_map : null, + space_colon : true, + unescape_regexps : false, + width : 80, + wrap_iife : false, + }, true); + + // Convert comment option to RegExp if neccessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + var comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } + else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } + else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = ""; + + function to_ascii(str, identifier) { + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i){ + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-7]/.test(str.charAt(i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + if (options.ascii_only) str = to_ascii(str); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + }; + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + }; + + function make_name(name) { + name = name.toString(); + if (options.ascii_only) + name = to_ascii(name, true); + return name; + }; + + function make_indent(back) { + return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); + }; + + /* -----[ beautification/minification ]----- */ + + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var last = ""; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + var left = OUTPUT.slice(0, might_add_newline); + var right = OUTPUT.slice(might_add_newline); + OUTPUT = left + "\n" + right; + current_line++; + current_pos++; + current_col = right.length; + } + if (current_col > options.max_line_len) { + AST_Node.warn("Output exceeds {max_line_len} characters", options); + } + } + might_add_newline = 0; + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , ."); + + function print(str) { + str = String(str); + var ch = str.charAt(0); + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") { + if (options.semicolons || requireSemicolonChars(ch)) { + OUTPUT += ";"; + current_col++; + current_pos++; + } else { + ensure_line_len(); + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { + var target_line = stack[stack.length - 1].start.line; + while (current_line < target_line) { + ensure_line_len(); + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last)) + { + OUTPUT += " "; + current_col++; + current_pos++; + } + might_need_space = false; + } + OUTPUT += str; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont() }; + + var newline = options.beautify ? function() { + print("\n"); + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length; + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + }; + + function next_indent() { + return indentation + options.indent_level; + }; + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function(){ + ret = cont(); + }); + indent(); + print("}"); + return ret; + }; + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + }; + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + }; + + function comma() { + print(","); + space(); + }; + + function colon() { + print(":"); + if (options.space_colon) space(); + }; + + var add_mapping = options.source_map ? function(token, name) { + try { + if (token) options.source_map.add( + token.file || "?", + current_line, current_col, + token.line, token.col, + (!name && token.type == "name") ? token.value : name + ); + } catch(ex) { + AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { + file: token.file, + line: token.line, + col: token.col, + cline: current_line, + ccol: current_col, + name: name || "" + }) + } + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT; + }; + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + indentation : function() { return indentation }, + current_width : function() { return current_col - indentation }, + should_break : function() { return options.width && this.current_width() >= options.width }, + newline : newline, + print : print, + space : space, + comma : comma, + colon : colon, + last : function() { return last }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_ascii : to_ascii, + print_name : function(name) { print(make_name(name)) }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && encoded.indexOf("\\") === -1) { + // Insert semicolons to break directive prologue + if (!EXPECT_DIRECTIVE.test(OUTPUT)) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt] }, + comment_filter : comment_filter, + line : function() { return current_line }, + col : function() { return current_col }, + pos : function() { return current_pos }, + push_node : function(node) { stack.push(node) }, + pop_node : function() { return stack.pop() }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +}; + +/* -----[ code generators ]----- */ + +(function(){ + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + }; + + var use_asm = false; + var in_directive = false; + + AST_Node.DEFMETHOD("print", function(stream, force_parens){ + var self = this, generator = self._codegen, prev_use_asm = use_asm; + if (self instanceof AST_Directive && self.value == "use asm" && stream.parent() instanceof AST_Scope) { + use_asm = true; + } + function doit() { + self.add_comments(stream); + self.add_source_map(stream); + generator(self, stream); + } + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(doit); + } else { + doit(); + } + stream.pop_node(); + if (self instanceof AST_Scope) { + use_asm = prev_use_asm; + } + }); + + AST_Node.DEFMETHOD("print_to_string", function(options){ + var s = OutputStream(options); + if (!options) s._readonly = true; + this.print(s); + return s.get(); + }); + + /* -----[ comments ]----- */ + + AST_Node.DEFMETHOD("add_comments", function(output){ + if (output._readonly) return; + var self = this; + var start = self.start; + if (start && !start._comments_dumped) { + start._comments_dumped = true; + var comments = start.comments_before || []; + + // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 + // and https://github.com/mishoo/UglifyJS2/issues/372 + if (self instanceof AST_Exit && self.value) { + self.value.walk(new TreeWalker(function(node){ + if (node.start && node.start.comments_before) { + comments = comments.concat(node.start.comments_before); + node.start.comments_before = []; + } + if (node instanceof AST_Function || + node instanceof AST_Array || + node instanceof AST_Object) + { + return true; // don't go inside. + } + })); + } + + if (output.pos() == 0) { + if (comments.length > 0 && output.option("shebang") && comments[0].type == "comment5") { + output.print("#!" + comments.shift().value + "\n"); + output.indent(); + } + var preamble = output.option("preamble"); + if (preamble) { + output.print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(output.comment_filter, self); + + // Keep single line comments after nlb, after nlb + if (!output.option("beautify") && comments.length > 0 && + /comment[134]/.test(comments[0].type) && + output.col() !== 0 && comments[0].nlb) + { + output.print("\n"); + } + + comments.forEach(function(c){ + if (/comment[134]/.test(c.type)) { + output.print("//" + c.value + "\n"); + output.indent(); + } + else if (c.type == "comment2") { + output.print("/*" + c.value + "*/"); + if (start.nlb) { + output.print("\n"); + output.indent(); + } else { + output.space(); + } + } + }); + } + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype){ + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + }; + + PARENS(AST_Node, function(){ + return false; + }); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output){ + if (first_in_statement(output)) { + return true; + } + + if (output.option('wrap_iife')) { + var p = output.parent(); + return p instanceof AST_Call && p.expression === this; + } + + return false; + }); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + PARENS(AST_Object, function(output){ + return first_in_statement(output); + }); + + PARENS(AST_Unary, function(output){ + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this; + }); + + PARENS(AST_Seq, function(output){ + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + ; + }); + + PARENS(AST_Binary, function(output){ + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && this === p.right)) { + return true; + } + } + }); + + PARENS(AST_PropAccess, function(output){ + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + try { + this.walk(new TreeWalker(function(node){ + if (node instanceof AST_Call) throw p; + })); + } catch(ex) { + if (ex !== p) throw ex; + return true; + } + } + }); + + PARENS(AST_Call, function(output){ + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output){ + var p = output.parent(); + if (!need_constructor_parens(this, output) + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output){ + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function (output){ + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output){ + output.print_string(self.value, self.quote); + output.semicolon(); + }); + DEFPRINT(AST_Debugger, function(self, output){ + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + in_directive = allow_directives; + body.forEach(function(stmt, i){ + if (in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + in_directive = false; + } + }); + in_directive = false; + }; + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output){ + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output){ + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + function print_bracketed(body, output, allow_directives) { + if (body.length > 0) output.with_block(function(){ + display_body(body, false, output, allow_directives); + }); + else output.print("{}"); + }; + DEFPRINT(AST_BlockStatement, function(self, output){ + print_bracketed(self.body, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output){ + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output){ + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output){ + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + self.init.print(output); + output.space(); + output.print("in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output){ + output.print("with"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ + var self = this; + if (!nokeyword) { + output.print("function"); + } + if (self.name) { + output.space(); + self.name.print(output); + } + output.with_parens(function(){ + self.argnames.forEach(function(arg, i){ + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_bracketed(self.body, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output){ + self._do_print(output); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.value) { + output.space(); + this.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output){ + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output){ + self._do_print(output, "throw"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output){ + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output){ + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("bracketize") + || !output.option("screw_ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block brackets if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } + else if (b instanceof AST_StatementWithBody) { + b = b.body; + } + else break; + } + force_statement(self.body, output); + }; + DEFPRINT(AST_If, function(self, output){ + output.print("if"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output){ + output.print("switch"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) output.print("{}"); + else output.with_block(function(){ + self.body.forEach(function(branch, i){ + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ + output.newline(); + this.body.forEach(function(stmt){ + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output){ + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output){ + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output){ + output.print("try"); + output.space(); + print_bracketed(self.body, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output){ + output.print("catch"); + output.space(); + output.with_parens(function(){ + self.argname.print(output); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Finally, function(self, output){ + output.print("finally"); + output.space(); + print_bracketed(self.body, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i){ + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var avoid_semicolon = in_for && p.init === this; + if (!avoid_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Var, function(self, output){ + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output){ + self._do_print(output, "const"); + }); + + function parenthesize_for_noin(node, output, noin) { + if (!noin) node.print(output); + else try { + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw output; + })); + node.print(output); + } catch(ex) { + if (ex !== output) throw ex; + node.print(output, true); + } + }; + + DEFPRINT(AST_VarDef, function(self, output){ + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output){ + self.expression.print(output); + if (self instanceof AST_New && !need_constructor_parens(self, output)) + return; + output.with_parens(function(){ + self.args.forEach(function(expr, i){ + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output){ + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Seq.DEFMETHOD("_do_print", function(output){ + this.car.print(output); + if (this.cdr) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + this.cdr.print(output); + } + }); + DEFPRINT(AST_Seq, function(self, output){ + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output){ + var expr = self.expression; + expr.print(output); + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(self.property); + }); + DEFPRINT(AST_Sub, function(self, output){ + self.expression.print(output); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output){ + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output){ + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output){ + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting <!-- + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(self, output){ + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(self, output){ + output.with_square(function(){ + var a = self.elements, len = a.length; + if (len > 0) output.space(); + a.forEach(function(exp, i){ + if (i) output.comma(); + exp.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i === len - 1 && exp instanceof AST_Hole) + output.comma(); + }); + if (len > 0) output.space(); + }); + }); + DEFPRINT(AST_Object, function(self, output){ + if (self.properties.length > 0) output.with_block(function(){ + self.properties.forEach(function(prop, i){ + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else output.print("{}"); + }); + + function print_property_name(key, quote, output) { + if (output.option("quote_keys")) { + output.print_string(key + ""); + } else if ((typeof key == "number" + || !output.option("beautify") + && +key + "" == key) + && parseFloat(key) >= 0) { + output.print(make_num(key)); + } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) { + if (quote && output.option("keep_quoted_props")) { + output.print_string(key, quote); + } else { + output.print_name(key); + } + } else { + output.print_string(key, quote); + } + } + + DEFPRINT(AST_ObjectKeyVal, function(self, output){ + print_property_name(self.key, self.quote, output); + output.colon(); + self.value.print(output); + }); + AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, output) { + output.print(type); + output.space(); + print_property_name(this.key.name, this.quote, output); + this.value._do_print(output, true); + }); + DEFPRINT(AST_ObjectSetter, function(self, output){ + self._print_getter_setter("set", output); + }); + DEFPRINT(AST_ObjectGetter, function(self, output){ + self._print_getter_setter("get", output); + }); + DEFPRINT(AST_Symbol, function(self, output){ + var def = self.definition(); + output.print_name(def ? def.mangled_name || def.name : self.name); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_This, function(self, output){ + output.print("this"); + }); + DEFPRINT(AST_Constant, function(self, output){ + output.print(self.getValue()); + }); + DEFPRINT(AST_String, function(self, output){ + output.print_string(self.getValue(), self.quote, in_directive); + }); + DEFPRINT(AST_Number, function(self, output){ + if (use_asm && self.start && self.start.raw != null) { + output.print(self.start.raw); + } else { + output.print(make_num(self.getValue())); + } + }); + + function regexp_safe_literal(code) { + return [ + 0x5c , // \ + 0x2f , // / + 0x2e , // . + 0x2b , // + + 0x2a , // * + 0x3f , // ? + 0x28 , // ( + 0x29 , // ) + 0x5b , // [ + 0x5d , // ] + 0x7b , // { + 0x7d , // } + 0x24 , // $ + 0x5e , // ^ + 0x3a , // : + 0x7c , // | + 0x21 , // ! + 0x0a , // \n + 0x0d , // \r + 0x00 , // \0 + 0xfeff , // Unicode BOM + 0x2028 , // unicode "line separator" + 0x2029 , // unicode "paragraph separator" + ].indexOf(code) < 0; + }; + + DEFPRINT(AST_RegExp, function(self, output){ + var str = self.getValue().toString(); + if (output.option("ascii_only")) { + str = output.to_ascii(str); + } else if (output.option("unescape_regexps")) { + str = str.split("\\\\").map(function(str){ + return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){ + var code = parseInt(s.substr(2), 16); + return regexp_safe_literal(code) ? String.fromCharCode(code) : s; + }); + }).join("\\\\"); + } + output.print(str); + var p = output.parent(); + if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self) + output.print(" "); + }); + + function force_statement(stat, output) { + if (output.option("bracketize")) { + make_block(stat, output); + } else { + if (!stat || stat instanceof AST_EmptyStatement) + output.force_semicolon(); + else + stat.print(output); + } + }; + + // self should be AST_New. decide if we want to show parens or not. + function need_constructor_parens(self, output) { + // Always print parentheses with arguments + if (self.args.length > 0) return true; + + return output.option("beautify"); + }; + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + }; + + function make_num(num) { + var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m; + if (Math.floor(num) === num) { + if (num >= 0) { + a.push("0x" + num.toString(16).toLowerCase(), // probably pointless + "0" + num.toString(8)); // same. + } else { + a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless + "-0" + (-num).toString(8)); // same. + } + if ((m = /^(.*?)(0+)$/.exec(num))) { + a.push(m[1] + "e" + m[2].length); + } + } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { + a.push(m[2] + "e-" + (m[1].length + m[2].length), + str.substr(str.indexOf("."))); + } + return best_of(a); + }; + + function make_block(stmt, output) { + if (!stmt || stmt instanceof AST_EmptyStatement) + output.print("{}"); + else if (stmt instanceof AST_BlockStatement) + stmt.print(output); + else output.with_block(function(){ + output.indent(); + stmt.print(output); + output.newline(); + }); + }; + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.DEFMETHOD("add_source_map", function(stream){ + generator(this, stream); + }); + }; + + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + DEFMAP(AST_Node, noop); + + function basic_sourcemap_gen(self, output) { + output.add_mapping(self.start); + }; + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + + DEFMAP(AST_Directive, basic_sourcemap_gen); + DEFMAP(AST_Debugger, basic_sourcemap_gen); + DEFMAP(AST_Symbol, basic_sourcemap_gen); + DEFMAP(AST_Jump, basic_sourcemap_gen); + DEFMAP(AST_StatementWithBody, basic_sourcemap_gen); + DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it + DEFMAP(AST_Lambda, basic_sourcemap_gen); + DEFMAP(AST_Switch, basic_sourcemap_gen); + DEFMAP(AST_SwitchBranch, basic_sourcemap_gen); + DEFMAP(AST_BlockStatement, basic_sourcemap_gen); + DEFMAP(AST_Toplevel, noop); + DEFMAP(AST_New, basic_sourcemap_gen); + DEFMAP(AST_Try, basic_sourcemap_gen); + DEFMAP(AST_Catch, basic_sourcemap_gen); + DEFMAP(AST_Finally, basic_sourcemap_gen); + DEFMAP(AST_Definitions, basic_sourcemap_gen); + DEFMAP(AST_Constant, basic_sourcemap_gen); + DEFMAP(AST_ObjectSetter, function(self, output){ + output.add_mapping(self.start, self.key.name); + }); + DEFMAP(AST_ObjectGetter, function(self, output){ + output.add_mapping(self.start, self.key.name); + }); + DEFMAP(AST_ObjectProperty, function(self, output){ + output.add_mapping(self.start, self.key); + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function Compressor(options, false_by_default) { + if (!(this instanceof Compressor)) + return new Compressor(options, false_by_default); + TreeTransformer.call(this, this.before, this.after); + this.options = defaults(options, { + angular : false, + booleans : !false_by_default, + cascade : !false_by_default, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + evaluate : !false_by_default, + expression : false, + global_defs : {}, + hoist_funs : !false_by_default, + hoist_vars : false, + if_return : !false_by_default, + join_vars : !false_by_default, + keep_fargs : true, + keep_fnames : false, + keep_infinity : false, + loops : !false_by_default, + negate_iife : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_getters : !false_by_default && "strict", + pure_funcs : null, + reduce_vars : !false_by_default, + screw_ie8 : true, + sequences : !false_by_default, + side_effects : !false_by_default, + switches : !false_by_default, + top_retain : null, + toplevel : !!(options && options["top_retain"]), + unsafe : false, + unsafe_comps : false, + unsafe_math : false, + unsafe_proto : false, + unsafe_regexp : false, + unused : !false_by_default, + warnings : true, + }, true); + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else { + this.pure_funcs = pure_funcs ? function(node) { + return pure_funcs.indexOf(node.expression.print_to_string()) < 0; + } : return_true; + } + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return top_retain.indexOf(def.name) >= 0; + }; + } + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 200 : sequences | 0; + this.warnings_produced = {}; +}; + +Compressor.prototype = new TreeTransformer; +merge(Compressor.prototype, { + option: function(key) { return this.options[key] }, + compress: function(node) { + if (this.option("expression")) { + node = node.process_expression(true); + } + var passes = +this.options.passes || 1; + for (var pass = 0; pass < passes && pass < 3; ++pass) { + if (pass > 0 || this.option("reduce_vars")) + node.reset_opt_flags(this, true); + node = node.transform(this); + } + if (this.option("expression")) { + node = node.process_expression(false); + } + return node; + }, + info: function() { + if (this.options.warnings == "verbose") { + AST_Node.warn.apply(AST_Node, arguments); + } + }, + warn: function(text, props) { + if (this.options.warnings) { + // only emit unique warnings + var message = string_template(text, props); + if (!(message in this.warnings_produced)) { + this.warnings_produced[message] = true; + AST_Node.warn.apply(AST_Node, arguments); + } + } + }, + clear_warnings: function() { + this.warnings_produced = {}; + }, + before: function(node, descend, in_list) { + if (node._squeezed) return node; + var was_scope = false; + if (node instanceof AST_Scope) { + node = node.hoist_declarations(this); + was_scope = true; + } + // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after OPT(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (was_scope && opt instanceof AST_Scope) { + opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) opt._squeezed = true; + return opt; + } +}); + +(function(){ + + function OPT(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor){ + var self = this; + if (self._optimized) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + opt._optimized = true; + return opt; + }); + }; + + OPT(AST_Node, function(self, compressor){ + return self; + }); + + AST_Node.DEFMETHOD("equivalent_to", function(node){ + return this.TYPE == node.TYPE && this.print_to_string() == node.print_to_string(); + }); + + AST_Node.DEFMETHOD("process_expression", function(insert, compressor) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert && node instanceof AST_SimpleStatement) { + return make_node(AST_Return, node, { + value: node.body + }); + } + if (!insert && node instanceof AST_Return) { + if (compressor) { + var value = node.value && node.value.drop_side_effect_free(compressor, true); + return value ? make_node(AST_SimpleStatement, node, { + body: value + }) : make_node(AST_EmptyStatement, node); + } + return make_node(AST_SimpleStatement, node, { + body: node.value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { + value: 0 + }) + }) + }); + } + if (node instanceof AST_Lambda && node !== self) { + return node; + } + if (node instanceof AST_Block) { + var index = node.body.length - 1; + if (index >= 0) { + node.body[index] = node.body[index].transform(tt); + } + } + if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) { + node.alternative = node.alternative.transform(tt); + } + } + if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + return self.transform(tt); + }); + + AST_Node.DEFMETHOD("reset_opt_flags", function(compressor, rescan){ + var reduce_vars = rescan && compressor.option("reduce_vars"); + var toplevel = compressor.option("toplevel"); + var safe_ids = Object.create(null); + var suppressor = new TreeWalker(function(node) { + if (node instanceof AST_Symbol) { + var d = node.definition(); + if (node instanceof AST_SymbolRef) d.references.push(node); + d.fixed = false; + } + }); + var tw = new TreeWalker(function(node, descend){ + node._squeezed = false; + node._optimized = false; + if (reduce_vars) { + if (node instanceof AST_Toplevel) node.globals.each(reset_def); + if (node instanceof AST_Scope) node.variables.each(reset_def); + if (node instanceof AST_SymbolRef) { + var d = node.definition(); + d.references.push(node); + if (d.fixed === undefined || !is_safe(d) + || is_modified(node, 0, node.fixed_value() instanceof AST_Lambda)) { + d.fixed = false; + } else { + var parent = tw.parent(); + if (parent instanceof AST_Assign && parent.operator == "=" && node === parent.right + || parent instanceof AST_Call && node !== parent.expression + || parent instanceof AST_Return && node === parent.value && node.scope !== d.scope + || parent instanceof AST_VarDef && node === parent.value) { + d.escaped = true; + } + } + } + if (node instanceof AST_SymbolCatch) { + node.definition().fixed = false; + } + if (node instanceof AST_VarDef) { + var d = node.name.definition(); + if (d.fixed == null) { + if (node.value) { + d.fixed = function() { + return node.value; + }; + mark(d, false); + descend(); + } else { + d.fixed = null; + } + mark(d, true); + return true; + } else if (node.value) { + d.fixed = false; + } + } + if (node instanceof AST_Defun) { + var d = node.name.definition(); + if (!toplevel && d.global || is_safe(d)) { + d.fixed = false; + } else { + d.fixed = node; + mark(d, true); + } + var save_ids = safe_ids; + safe_ids = Object.create(null); + descend(); + safe_ids = save_ids; + return true; + } + if (node instanceof AST_Function) { + push(); + var iife; + if (!node.name + && (iife = tw.parent()) instanceof AST_Call + && iife.expression === node) { + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + node.argnames.forEach(function(arg, i) { + var d = arg.definition(); + if (!node.uses_arguments && d.fixed === undefined) { + d.fixed = function() { + return iife.args[i] || make_node(AST_Undefined, iife); + }; + mark(d, true); + } else { + d.fixed = false; + } + }); + } + descend(); + pop(); + return true; + } + if (node instanceof AST_Accessor) { + var save_ids = safe_ids; + safe_ids = Object.create(null); + descend(); + safe_ids = save_ids; + return true; + } + if (node instanceof AST_Binary + && (node.operator == "&&" || node.operator == "||")) { + node.left.walk(tw); + push(); + node.right.walk(tw); + pop(); + return true; + } + if (node instanceof AST_Conditional) { + node.condition.walk(tw); + push(); + node.consequent.walk(tw); + pop(); + push(); + node.alternative.walk(tw); + pop(); + return true; + } + if (node instanceof AST_If || node instanceof AST_DWLoop) { + node.condition.walk(tw); + push(); + node.body.walk(tw); + pop(); + if (node.alternative) { + push(); + node.alternative.walk(tw); + pop(); + } + return true; + } + if (node instanceof AST_LabeledStatement) { + push(); + node.body.walk(tw); + pop(); + return true; + } + if (node instanceof AST_For) { + if (node.init) node.init.walk(tw); + push(); + if (node.condition) node.condition.walk(tw); + node.body.walk(tw); + if (node.step) node.step.walk(tw); + pop(); + return true; + } + if (node instanceof AST_ForIn) { + node.init.walk(suppressor); + node.object.walk(tw); + push(); + node.body.walk(tw); + pop(); + return true; + } + if (node instanceof AST_Try) { + push(); + walk_body(node, tw); + pop(); + if (node.bcatch) { + push(); + node.bcatch.walk(tw); + pop(); + } + if (node.bfinally) node.bfinally.walk(tw); + return true; + } + if (node instanceof AST_SwitchBranch) { + push(); + descend(); + pop(); + return true; + } + } + }); + this.walk(tw); + + function mark(def, safe) { + safe_ids[def.id] = safe; + } + + function is_safe(def) { + if (safe_ids[def.id]) { + if (def.fixed == null) { + var orig = def.orig[0]; + if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false; + def.fixed = make_node(AST_Undefined, orig); + } + return true; + } + } + + function push() { + safe_ids = Object.create(safe_ids); + } + + function pop() { + safe_ids = Object.getPrototypeOf(safe_ids); + } + + function reset_def(def) { + def.escaped = false; + if (def.scope.uses_eval) { + def.fixed = false; + } else if (toplevel || !def.global || def.orig[0] instanceof AST_SymbolConst) { + def.fixed = undefined; + } else { + def.fixed = false; + } + def.references = []; + def.should_replace = undefined; + } + + function is_modified(node, level, func) { + var parent = tw.parent(level); + if (is_lhs(node, parent) + || !func && parent instanceof AST_Call && parent.expression === node) { + return true; + } else if (parent instanceof AST_PropAccess && parent.expression === node) { + return !func && is_modified(parent, level + 1); + } + } + }); + + AST_SymbolRef.DEFMETHOD("fixed_value", function() { + var fixed = this.definition().fixed; + if (!fixed || fixed instanceof AST_Node) return fixed; + return fixed(); + }); + + function is_reference_const(ref) { + if (!(ref instanceof AST_SymbolRef)) return false; + var orig = ref.definition().orig; + for (var i = orig.length; --i >= 0;) { + if (orig[i] instanceof AST_SymbolConst) return true; + } + } + + function find_variable(compressor, name) { + var scope, i = 0; + while (scope = compressor.parent(i++)) { + if (scope instanceof AST_Scope) break; + if (scope instanceof AST_Catch) { + scope = scope.argname.definition().scope; + break; + } + } + return scope.find_variable(name); + } + + function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); + }; + + function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }) + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig) + }) : make_node(AST_Infinity, orig); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig, { value: null }); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { value: val }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } + }; + + // we shouldn't compress (1,func)(something) to + // func(something) because that changes the meaning of + // the func (becomes lexical instead of global). + function maintain_this_binding(parent, orig, val) { + if (parent instanceof AST_UnaryPrefix && parent.operator == "delete" + || parent instanceof AST_Call && parent.expression === orig + && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) { + return make_node(AST_Seq, orig, { + car: make_node(AST_Number, orig, { + value: 0 + }), + cdr: val + }); + } + return val; + } + + function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); + }; + + function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; + }; + + function loop_body(x) { + if (x instanceof AST_Switch) return x; + if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { + return (x.body instanceof AST_BlockStatement ? x.body : x); + } + return x; + }; + + function is_iife_call(node) { + if (node instanceof AST_Call && !(node instanceof AST_New)) { + return node.expression instanceof AST_Function || is_iife_call(node.expression); + } + return false; + } + + function tighten_body(statements, compressor) { + var CHANGED, max_iter = 10; + do { + CHANGED = false; + if (compressor.option("angular")) { + statements = process_for_angular(statements); + } + statements = eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + statements = eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + statements = handle_if_return(statements, compressor); + } + if (compressor.sequences_limit > 0) { + statements = sequencesize(statements, compressor); + } + if (compressor.option("join_vars")) { + statements = join_consecutive_vars(statements, compressor); + } + if (compressor.option("collapse_vars")) { + statements = collapse_single_use_vars(statements, compressor); + } + } while (CHANGED && max_iter-- > 0); + + return statements; + + function collapse_single_use_vars(statements, compressor) { + // Iterate statements backwards looking for a statement with a var/const + // declaration immediately preceding it. Grab the rightmost var definition + // and if it has exactly one reference then attempt to replace its reference + // in the statement with the var value and then erase the var definition. + + var self = compressor.self(); + var var_defs_removed = false; + var toplevel = compressor.option("toplevel"); + for (var stat_index = statements.length; --stat_index >= 0;) { + var stat = statements[stat_index]; + if (stat instanceof AST_Definitions) continue; + + // Process child blocks of statement if present. + [stat, stat.body, stat.alternative, stat.bcatch, stat.bfinally].forEach(function(node) { + node && node.body && collapse_single_use_vars(node.body, compressor); + }); + + // The variable definition must precede a statement. + if (stat_index <= 0) break; + var prev_stat_index = stat_index - 1; + var prev_stat = statements[prev_stat_index]; + if (!(prev_stat instanceof AST_Definitions)) continue; + var var_defs = prev_stat.definitions; + if (var_defs == null) continue; + + var var_names_seen = {}; + var side_effects_encountered = false; + var lvalues_encountered = false; + var lvalues = {}; + + // Scan variable definitions from right to left. + for (var var_defs_index = var_defs.length; --var_defs_index >= 0;) { + + // Obtain var declaration and var name with basic sanity check. + var var_decl = var_defs[var_defs_index]; + if (var_decl.value == null) break; + var var_name = var_decl.name.name; + if (!var_name || !var_name.length) break; + + // Bail if we've seen a var definition of same name before. + if (var_name in var_names_seen) break; + var_names_seen[var_name] = true; + + // Only interested in cases with just one reference to the variable. + var def = self.find_variable && self.find_variable(var_name); + if (!def || !def.references || def.references.length !== 1 + || var_name == "arguments" || (!toplevel && def.global)) { + side_effects_encountered = true; + continue; + } + var ref = def.references[0]; + + // Don't replace ref if eval() or with statement in scope. + if (ref.scope.uses_eval || ref.scope.uses_with) break; + + // Constant single use vars can be replaced in any scope. + if (var_decl.value.is_constant()) { + var ctt = new TreeTransformer(function(node) { + var parent = ctt.parent(); + if (parent instanceof AST_IterationStatement + && (parent.condition === node || parent.init === node)) { + return node; + } + if (node === ref) + return replace_var(node, parent, true); + }); + stat.transform(ctt); + continue; + } + + // Restrict var replacement to constants if side effects encountered. + if (side_effects_encountered |= lvalues_encountered) continue; + + var value_has_side_effects = var_decl.value.has_side_effects(compressor); + // Non-constant single use vars can only be replaced in same scope. + if (ref.scope !== self) { + side_effects_encountered |= value_has_side_effects; + continue; + } + + // Detect lvalues in var value. + var tw = new TreeWalker(function(node){ + if (node instanceof AST_SymbolRef && is_lvalue(node, tw.parent())) { + lvalues[node.name] = lvalues_encountered = true; + } + }); + var_decl.value.walk(tw); + + // Replace the non-constant single use var in statement if side effect free. + var unwind = false; + var tt = new TreeTransformer( + function preorder(node) { + if (unwind) return node; + var parent = tt.parent(); + if (node instanceof AST_Lambda + || node instanceof AST_Try + || node instanceof AST_With + || node instanceof AST_Case + || node instanceof AST_IterationStatement + || (parent instanceof AST_If && node !== parent.condition) + || (parent instanceof AST_Conditional && node !== parent.condition) + || (node instanceof AST_SymbolRef + && value_has_side_effects + && !are_references_in_scope(node.definition(), self)) + || (parent instanceof AST_Binary + && (parent.operator == "&&" || parent.operator == "||") + && node === parent.right) + || (parent instanceof AST_Switch && node !== parent.expression)) { + return side_effects_encountered = unwind = true, node; + } + function are_references_in_scope(def, scope) { + if (def.orig.length === 1 + && def.orig[0] instanceof AST_SymbolDefun) return true; + if (def.scope !== scope) return false; + var refs = def.references; + for (var i = 0, len = refs.length; i < len; i++) { + if (refs[i].scope !== scope) return false; + } + return true; + } + }, + function postorder(node) { + if (unwind) return node; + if (node === ref) + return unwind = true, replace_var(node, tt.parent(), false); + if (side_effects_encountered |= node.has_side_effects(compressor)) + return unwind = true, node; + if (lvalues_encountered && node instanceof AST_SymbolRef && node.name in lvalues) { + side_effects_encountered = true; + return unwind = true, node; + } + } + ); + stat.transform(tt); + } + } + + // Remove extraneous empty statments in block after removing var definitions. + // Leave at least one statement in `statements`. + if (var_defs_removed) for (var i = statements.length; --i >= 0;) { + if (statements.length > 1 && statements[i] instanceof AST_EmptyStatement) + statements.splice(i, 1); + } + + return statements; + + function is_lvalue(node, parent) { + return node instanceof AST_SymbolRef && is_lhs(node, parent); + } + function replace_var(node, parent, is_constant) { + if (is_lvalue(node, parent)) return node; + + // Remove var definition and return its value to the TreeTransformer to replace. + var value = maintain_this_binding(parent, node, var_decl.value); + var_decl.value = null; + + var_defs.splice(var_defs_index, 1); + if (var_defs.length === 0) { + statements[prev_stat_index] = make_node(AST_EmptyStatement, self); + var_defs_removed = true; + } + // Further optimize statement after substitution. + stat.reset_opt_flags(compressor); + + compressor.info("Collapsing " + (is_constant ? "constant" : "variable") + + " " + var_name + " [{file}:{line},{col}]", node.start); + CHANGED = true; + return value; + } + } + + function process_for_angular(statements) { + function has_inject(comment) { + return /@ngInject/.test(comment.value); + } + function make_arguments_names_list(func) { + return func.argnames.map(function(sym){ + return make_node(AST_String, sym, { value: sym.name }); + }); + } + function make_array(orig, elements) { + return make_node(AST_Array, orig, { elements: elements }); + } + function make_injector(func, name) { + return make_node(AST_SimpleStatement, func, { + body: make_node(AST_Assign, func, { + operator: "=", + left: make_node(AST_Dot, name, { + expression: make_node(AST_SymbolRef, name, name), + property: "$inject" + }), + right: make_array(func, make_arguments_names_list(func)) + }) + }); + } + function check_expression(body) { + if (body && body.args) { + // if this is a function call check all of arguments passed + body.args.forEach(function(argument, index, array) { + var comments = argument.start.comments_before; + // if the argument is function preceded by @ngInject + if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) { + // replace the function with an array of names of its parameters and function at the end + array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument)); + } + }); + // if this is chained call check previous one recursively + if (body.expression && body.expression.expression) { + check_expression(body.expression.expression); + } + } + } + return statements.reduce(function(a, stat){ + a.push(stat); + + if (stat.body && stat.body.args) { + check_expression(stat.body); + } else { + var token = stat.start; + var comments = token.comments_before; + if (comments && comments.length > 0) { + var last = comments.pop(); + if (has_inject(last)) { + // case 1: defun + if (stat instanceof AST_Defun) { + a.push(make_injector(stat, stat.name)); + } + else if (stat instanceof AST_Definitions) { + stat.definitions.forEach(function(def) { + if (def.value && def.value instanceof AST_Lambda) { + a.push(make_injector(def.value, def.name)); + } + }); + } + else { + compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token); + } + } + } + } + + return a; + }, []); + } + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_BlockStatement) { + CHANGED = true; + a.push.apply(a, eliminate_spurious_blocks(stat.body)); + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + a.push(stat); + seen_dirs.push(stat.value); + } else { + CHANGED = true; + } + } else { + a.push(stat); + } + return a; + }, []); + }; + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var multiple_if_returns = has_multiple_if_returns(statements); + var in_lambda = self instanceof AST_Lambda; + var ret = []; // Optimized statements, build from tail to front + loop: for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + switch (true) { + case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): + CHANGED = true; + // note, ret.length is probably always zero + // because we drop unreachable code before this + // step. nevertheless, it's good to check. + continue loop; + case stat instanceof AST_If: + if (stat.body instanceof AST_Return) { + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (((in_lambda && ret.length == 0) + || (ret[0] instanceof AST_Return && !ret[0].value)) + && !stat.body.value && !stat.alternative) { + CHANGED = true; + var cond = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + ret.unshift(cond); + continue loop; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0]; + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if (multiple_if_returns && (ret.length == 0 || ret[0] instanceof AST_Return) + && stat.body.value && !stat.alternative && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0] || make_node(AST_Return, stat, { + value: null + }); + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } + if (!stat.body.value && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + var body = as_statement_array(stat.alternative).concat(ret); + var funs = extract_functions_from_statement_array(body); + stat.body = make_node(AST_BlockStatement, stat, { + body: body + }); + stat.alternative = null; + ret = funs.concat([ stat.transform(compressor) ]); + continue loop; + } + + //--- + // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + if (compressor.option("sequences") + && i > 0 && statements[i - 1] instanceof AST_If && statements[i - 1].body instanceof AST_Return + && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement + && !stat.alternative) { + CHANGED = true; + ret.push(make_node(AST_Return, ret[0], { + value: null + }).transform(compressor)); + ret.unshift(stat); + continue loop; + } + } + + var ab = aborts(stat.body); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + var body = as_statement_array(stat.body).slice(0, -1); + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(ret) + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: body + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + var ab = aborts(stat.alternative); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(ret) + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: as_statement_array(stat.alternative).slice(0, -1) + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + ret.unshift(stat); + break; + default: + ret.unshift(stat); + break; + } + } + return ret; + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) return true; + } + } + return false; + } + }; + + function eliminate_dead_code(statements, compressor) { + var has_quit = false; + var orig = statements.length; + var self = compressor.self(); + statements = statements.reduce(function(a, stat){ + if (has_quit) { + extract_declarations_from_unreachable_code(compressor, stat, a); + } else { + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if ((stat instanceof AST_Break + && !(lct instanceof AST_IterationStatement) + && loop_body(lct) === self) || (stat instanceof AST_Continue + && loop_body(lct) === self)) { + if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + a.push(stat); + } + } else { + a.push(stat); + } + if (aborts(stat)) has_quit = true; + } + return a; + }, []); + CHANGED = statements.length != orig; + return statements; + }; + + function sequencesize(statements, compressor) { + if (statements.length < 2) return statements; + var seq = [], ret = []; + function push_seq() { + seq = AST_Seq.from_array(seq); + if (seq) ret.push(make_node(AST_SimpleStatement, seq, { + body: seq + })); + seq = []; + }; + statements.forEach(function(stat){ + if (stat instanceof AST_SimpleStatement) { + if (seqLength(seq) >= compressor.sequences_limit) push_seq(); + var body = stat.body; + if (seq.length > 0) body = body.drop_side_effect_free(compressor); + if (body) seq.push(body); + } else { + push_seq(); + ret.push(stat); + } + }); + push_seq(); + ret = sequencesize_2(ret, compressor); + CHANGED = ret.length != statements.length; + return ret; + }; + + function seqLength(a) { + for (var len = 0, i = 0; i < a.length; ++i) { + var stat = a[i]; + if (stat instanceof AST_Seq) { + len += stat.len(); + } else { + len++; + } + } + return len; + }; + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + ret.pop(); + var left = prev.body; + if (left instanceof AST_Seq) { + left.add(right); + } else { + left = AST_Seq.cons(left, right); + } + return left.transform(compressor); + }; + var ret = [], prev = null; + statements.forEach(function(stat){ + if (prev) { + if (stat instanceof AST_For) { + var opera = {}; + try { + prev.body.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw opera; + })); + if (stat.init && !(stat.init instanceof AST_Definitions)) { + stat.init = cons_seq(stat.init); + } + else if (!stat.init) { + stat.init = prev.body.drop_side_effect_free(compressor); + ret.pop(); + } + } catch(ex) { + if (ex !== opera) throw ex; + } + } + else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } + else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + else if (stat instanceof AST_Exit && stat.value) { + stat.value = cons_seq(stat.value); + } + else if (stat instanceof AST_Exit) { + stat.value = cons_seq(make_node(AST_Undefined, stat).transform(compressor)); + } + else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } + } + ret.push(stat); + prev = stat instanceof AST_SimpleStatement ? stat : null; + }); + return ret; + }; + + function join_consecutive_vars(statements, compressor) { + var prev = null; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } + else if (stat instanceof AST_For + && prev instanceof AST_Var + && (!stat.init || stat.init.TYPE == prev.TYPE)) { + CHANGED = true; + a.pop(); + if (stat.init) { + stat.init.definitions = prev.definitions.concat(stat.init.definitions); + } else { + stat.init = prev; + } + a.push(stat); + prev = stat; + } + else { + prev = stat; + a.push(stat); + } + return a; + }, []); + }; + + }; + + function extract_functions_from_statement_array(statements) { + var funs = []; + for (var i = statements.length - 1; i >= 0; --i) { + var stat = statements[i]; + if (stat instanceof AST_Defun) { + statements.splice(i, 1); + funs.unshift(stat); + } + } + return funs; + } + + function extract_declarations_from_unreachable_code(compressor, stat, target) { + if (!(stat instanceof AST_Defun)) { + compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); + } + stat.walk(new TreeWalker(function(node){ + if (node instanceof AST_Definitions) { + compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); + node.remove_initializers(); + target.push(node); + return true; + } + if (node instanceof AST_Defun) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + })); + }; + + function is_undefined(node, compressor) { + return node.is_undefined + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor); + } + + // may_throw_on_access() + // returns true if this node may be null, undefined or contain `AST_Accessor` + (function(def) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) { + var pure_getters = compressor.option("pure_getters"); + return !pure_getters || this._throw_on_access(pure_getters); + }); + + function is_strict(pure_getters) { + return /strict/.test(pure_getters); + } + + def(AST_Node, is_strict); + def(AST_Null, return_true); + def(AST_Undefined, return_true); + def(AST_Constant, return_false); + def(AST_Array, return_false); + def(AST_Object, function(pure_getters) { + if (!is_strict(pure_getters)) return false; + for (var i = this.properties.length; --i >=0;) + if (this.properties[i].value instanceof AST_Accessor) return true; + return false; + }); + def(AST_Function, return_false); + def(AST_UnaryPostfix, return_false); + def(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def(AST_Binary, function(pure_getters) { + switch (this.operator) { + case "&&": + return this.left._throw_on_access(pure_getters); + case "||": + return this.left._throw_on_access(pure_getters) + && this.right._throw_on_access(pure_getters); + default: + return false; + } + }) + def(AST_Assign, function(pure_getters) { + return this.operator == "=" + && this.right._throw_on_access(pure_getters); + }) + def(AST_Conditional, function(pure_getters) { + return this.consequent._throw_on_access(pure_getters) + || this.alternative._throw_on_access(pure_getters); + }) + def(AST_Seq, function(pure_getters) { + return this.cdr._throw_on_access(pure_getters); + }); + def(AST_SymbolRef, function(pure_getters) { + if (this.is_undefined) return true; + if (!is_strict(pure_getters)) return false; + var fixed = this.fixed_value(); + return !fixed || fixed._throw_on_access(pure_getters); + }); + })(function(node, func) { + node.DEFMETHOD("_throw_on_access", func); + }); + + /* -----[ boolean/negation helpers ]----- */ + + // methods to determine whether an expression has a boolean result type + (function (def){ + var unary_bool = [ "!", "delete" ]; + var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; + def(AST_Node, return_false); + def(AST_UnaryPrefix, function(){ + return member(this.operator, unary_bool); + }); + def(AST_Binary, function(){ + return member(this.operator, binary_bool) || + ( (this.operator == "&&" || this.operator == "||") && + this.left.is_boolean() && this.right.is_boolean() ); + }); + def(AST_Conditional, function(){ + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def(AST_Assign, function(){ + return this.operator == "=" && this.right.is_boolean(); + }); + def(AST_Seq, function(){ + return this.cdr.is_boolean(); + }); + def(AST_True, return_true); + def(AST_False, return_true); + })(function(node, func){ + node.DEFMETHOD("is_boolean", func); + }); + + // methods to determine if an expression has a numeric result type + (function (def){ + def(AST_Node, return_false); + def(AST_Number, return_true); + var unary = makePredicate("+ - ~ ++ --"); + def(AST_Unary, function(){ + return unary(this.operator); + }); + var binary = makePredicate("- * / % & | ^ << >> >>>"); + def(AST_Binary, function(compressor){ + return binary(this.operator) || this.operator == "+" + && this.left.is_number(compressor) + && this.right.is_number(compressor); + }); + def(AST_Assign, function(compressor){ + return binary(this.operator.slice(0, -1)) + || this.operator == "=" && this.right.is_number(compressor); + }); + def(AST_Seq, function(compressor){ + return this.cdr.is_number(compressor); + }); + def(AST_Conditional, function(compressor){ + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("is_number", func); + }); + + // methods to determine if an expression has a string result type + (function (def){ + def(AST_Node, return_false); + def(AST_String, return_true); + def(AST_UnaryPrefix, function(){ + return this.operator == "typeof"; + }); + def(AST_Binary, function(compressor){ + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def(AST_Assign, function(compressor){ + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def(AST_Seq, function(compressor){ + return this.cdr.is_string(compressor); + }); + def(AST_Conditional, function(compressor){ + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("is_string", func); + }); + + var unary_side_effects = makePredicate("delete ++ --"); + + function is_lhs(node, parent) { + if (parent instanceof AST_Unary && unary_side_effects(parent.operator)) return parent.expression; + if (parent instanceof AST_Assign && parent.left === node) return node; + } + + (function (def){ + AST_Node.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return; + var def = this._find_defs(compressor, ""); + if (def) { + var node, parent = this, level = 0; + do { + node = parent; + parent = compressor.parent(level++); + } while (parent instanceof AST_PropAccess && parent.expression === node); + if (is_lhs(node, parent)) { + compressor.warn('global_defs ' + this.print_to_string() + ' redefined [{file}:{line},{col}]', this.start); + } else { + return def; + } + } + }); + function to_node(value, orig) { + if (value instanceof AST_Node) return make_node(value.CTOR, orig, value); + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig) + })); + } + return make_node(AST_Object, orig, { + properties: props + }); + } + return make_node_from_constant(value, orig); + } + def(AST_Node, noop); + def(AST_Dot, function(compressor, suffix){ + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def(AST_SymbolRef, function(compressor, suffix){ + if (!this.global()) return; + var name; + var defines = compressor.option("global_defs"); + if (defines && HOP(defines, (name = this.name + suffix))) { + var node = to_node(defines[name], this); + var top = compressor.find_parent(AST_Toplevel); + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) { + node.scope = top; + node.thedef = top.def_global(node); + } + })); + return node; + } + }); + })(function(node, func){ + node.DEFMETHOD("_find_defs", func); + }); + + function best_of_expression(ast1, ast2) { + return ast1.print_to_string().length > + ast2.print_to_string().length + ? ast2 : ast1; + } + + function best_of_statement(ast1, ast2) { + return best_of_expression(make_node(AST_SimpleStatement, ast1, { + body: ast1 + }), make_node(AST_SimpleStatement, ast2, { + body: ast2 + })).body; + } + + function best_of(compressor, ast1, ast2) { + return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2); + } + + // methods to evaluate a constant expression + (function (def){ + // If the node has been successfully reduced to a constant, + // then its value is returned; otherwise the element itself + // is returned. + // They can be distinguished as constant value is never a + // descendant of AST_Node. + AST_Node.DEFMETHOD("evaluate", function(compressor){ + if (!compressor.option("evaluate")) return this; + try { + var val = this._eval(compressor); + return !val || val instanceof RegExp || typeof val != "object" ? val : this; + } catch(ex) { + if (ex !== def) throw ex; + return this; + } + }); + var unaryPrefix = makePredicate("! ~ - + void"); + AST_Node.DEFMETHOD("is_constant", function(){ + // Accomodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + if (this instanceof AST_Constant) { + return !(this instanceof AST_RegExp); + } else { + return this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant + && unaryPrefix(this.operator); + } + }); + // Obtain the constant value of an expression already known to be constant. + // Result only valid iff this.is_constant() is true. + AST_Node.DEFMETHOD("constant_value", function(compressor){ + // Accomodate when option evaluate=false. + if (this instanceof AST_Constant && !(this instanceof AST_RegExp)) { + return this.value; + } + // Accomodate the common constant expressions !0 and -1 when option evaluate=false. + if (this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant) switch (this.operator) { + case "!": + return !this.expression.value; + case "~": + return ~this.expression.value; + case "-": + return -this.expression.value; + case "+": + return +this.expression.value; + default: + throw new Error(string_template("Cannot evaluate unary expression {value}", { + value: this.print_to_string() + })); + } + var result = this.evaluate(compressor); + if (result !== this) { + return result; + } + throw new Error(string_template("Cannot evaluate constant [{file}:{line},{col}]", this.start)); + }); + def(AST_Statement, function(){ + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); + }); + def(AST_Lambda, function(){ + throw def; + }); + function ev(node, compressor) { + if (!compressor) throw new Error("Compressor must be passed"); + + return node._eval(compressor); + }; + def(AST_Node, function(){ + throw def; // not constant + }); + def(AST_Constant, function(){ + return this.getValue(); + }); + def(AST_Array, function(compressor){ + if (compressor.option("unsafe")) { + return this.elements.map(function(element) { + return ev(element, compressor); + }); + } + throw def; + }); + def(AST_Object, function(compressor){ + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0, len = this.properties.length; i < len; i++) { + var prop = this.properties[i]; + var key = prop.key; + if (key instanceof AST_Symbol) { + key = key.name; + } else if (key instanceof AST_Node) { + key = ev(key, compressor); + } + if (typeof Object.prototype[key] === 'function') { + throw def; + } + val[key] = ev(prop.value, compressor); + } + return val; + } + throw def; + }); + def(AST_UnaryPrefix, function(compressor){ + var e = this.expression; + switch (this.operator) { + case "!": return !ev(e, compressor); + case "typeof": + // Function would be evaluated to an array and so typeof would + // incorrectly return 'object'. Hence making is a special case. + if (e instanceof AST_Function) return typeof function(){}; + + e = ev(e, compressor); + + // typeof <RegExp> returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (e instanceof RegExp) throw def; + + return typeof e; + case "void": return void ev(e, compressor); + case "~": return ~ev(e, compressor); + case "-": return -ev(e, compressor); + case "+": return +ev(e, compressor); + } + throw def; + }); + def(AST_Binary, function(c){ + var left = this.left, right = this.right, result; + switch (this.operator) { + case "&&" : result = ev(left, c) && ev(right, c); break; + case "||" : result = ev(left, c) || ev(right, c); break; + case "|" : result = ev(left, c) | ev(right, c); break; + case "&" : result = ev(left, c) & ev(right, c); break; + case "^" : result = ev(left, c) ^ ev(right, c); break; + case "+" : result = ev(left, c) + ev(right, c); break; + case "*" : result = ev(left, c) * ev(right, c); break; + case "/" : result = ev(left, c) / ev(right, c); break; + case "%" : result = ev(left, c) % ev(right, c); break; + case "-" : result = ev(left, c) - ev(right, c); break; + case "<<" : result = ev(left, c) << ev(right, c); break; + case ">>" : result = ev(left, c) >> ev(right, c); break; + case ">>>" : result = ev(left, c) >>> ev(right, c); break; + case "==" : result = ev(left, c) == ev(right, c); break; + case "===" : result = ev(left, c) === ev(right, c); break; + case "!=" : result = ev(left, c) != ev(right, c); break; + case "!==" : result = ev(left, c) !== ev(right, c); break; + case "<" : result = ev(left, c) < ev(right, c); break; + case "<=" : result = ev(left, c) <= ev(right, c); break; + case ">" : result = ev(left, c) > ev(right, c); break; + case ">=" : result = ev(left, c) >= ev(right, c); break; + default: + throw def; + } + if (isNaN(result) && c.find_parent(AST_With)) { + // leave original expression as is + throw def; + } + return result; + }); + def(AST_Conditional, function(compressor){ + return ev(this.condition, compressor) + ? ev(this.consequent, compressor) + : ev(this.alternative, compressor); + }); + def(AST_SymbolRef, function(compressor){ + if (!compressor.option("reduce_vars") || this._evaluating) throw def; + this._evaluating = true; + try { + var fixed = this.fixed_value(); + if (!fixed) throw def; + var value = ev(fixed, compressor); + if (!HOP(fixed, "_eval")) fixed._eval = function() { + return value; + }; + if (value && typeof value == "object" && this.definition().escaped) throw def; + return value; + } finally { + this._evaluating = false; + } + }); + def(AST_PropAccess, function(compressor){ + if (compressor.option("unsafe")) { + var key = this.property; + if (key instanceof AST_Node) { + key = ev(key, compressor); + } + var val = ev(this.expression, compressor); + if (val && HOP(val, key)) { + return val[key]; + } + } + throw def; + }); + })(function(node, func){ + node.DEFMETHOD("_eval", func); + }); + + // method to negate an expression + (function(def){ + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) { + var stat = make_node(AST_SimpleStatement, alt, { + body: alt + }); + return best_of_expression(negated, stat) === stat ? alt : negated; + } + return best_of_expression(negated, alt); + } + def(AST_Node, function(){ + return basic_negation(this); + }); + def(AST_Statement, function(){ + throw new Error("Cannot negate a statement"); + }); + def(AST_Function, function(){ + return basic_negation(this); + }); + def(AST_UnaryPrefix, function(){ + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def(AST_Seq, function(compressor){ + var self = this.clone(); + self.cdr = self.cdr.negate(compressor); + return self; + }); + def(AST_Conditional, function(compressor, first_in_statement){ + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def(AST_Binary, function(compressor, first_in_statement){ + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); + })(function(node, func){ + node.DEFMETHOD("negate", function(compressor, first_in_statement){ + return func.call(this, compressor, first_in_statement); + }); + }); + + AST_Call.DEFMETHOD("has_pure_annotation", function(compressor) { + if (!compressor.option("side_effects")) return false; + if (this.pure !== undefined) return this.pure; + var pure = false; + var comments, last_comment; + if (this.start + && (comments = this.start.comments_before) + && comments.length + && /[@#]__PURE__/.test((last_comment = comments[comments.length - 1]).value)) { + pure = last_comment; + } + return this.pure = pure; + }); + + // determine if expression has side effects + (function(def){ + def(AST_Node, return_true); + + def(AST_EmptyStatement, return_false); + def(AST_Constant, return_false); + def(AST_This, return_false); + + def(AST_Call, function(compressor){ + if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) return true; + for (var i = this.args.length; --i >= 0;) { + if (this.args[i].has_side_effects(compressor)) + return true; + } + return false; + }); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].has_side_effects(compressor)) + return true; + return false; + } + + def(AST_Block, function(compressor){ + return any(this.body, compressor); + }); + def(AST_Switch, function(compressor){ + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_Case, function(compressor){ + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_Try, function(compressor){ + return any(this.body, compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def(AST_If, function(compressor){ + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def(AST_LabeledStatement, function(compressor){ + return this.body.has_side_effects(compressor); + }); + def(AST_SimpleStatement, function(compressor){ + return this.body.has_side_effects(compressor); + }); + def(AST_Defun, return_true); + def(AST_Function, return_false); + def(AST_Binary, function(compressor){ + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def(AST_Assign, return_true); + def(AST_Conditional, function(compressor){ + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def(AST_Unary, function(compressor){ + return unary_side_effects(this.operator) + || this.expression.has_side_effects(compressor); + }); + def(AST_SymbolRef, function(compressor){ + return this.undeclared(); + }); + def(AST_Object, function(compressor){ + return any(this.properties, compressor); + }); + def(AST_ObjectProperty, function(compressor){ + return this.value.has_side_effects(compressor); + }); + def(AST_Array, function(compressor){ + return any(this.elements, compressor); + }); + def(AST_Dot, function(compressor){ + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor); + }); + def(AST_Sub, function(compressor){ + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor) + || this.property.has_side_effects(compressor); + }); + def(AST_Seq, function(compressor){ + return this.car.has_side_effects(compressor) + || this.cdr.has_side_effects(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("has_side_effects", func); + }); + + // tell me if a statement aborts + function aborts(thing) { + return thing && thing.aborts(); + }; + (function(def){ + def(AST_Statement, return_null); + def(AST_Jump, return_this); + function block_aborts(){ + var n = this.body.length; + return n > 0 && aborts(this.body[n - 1]); + }; + def(AST_BlockStatement, block_aborts); + def(AST_SwitchBranch, block_aborts); + def(AST_If, function(){ + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); + })(function(node, func){ + node.DEFMETHOD("aborts", func); + }); + + /* -----[ optimizers ]----- */ + + OPT(AST_Directive, function(self, compressor){ + if (compressor.has_directive(self.value) !== self) { + return make_node(AST_EmptyStatement, self); + } + return self; + }); + + OPT(AST_Debugger, function(self, compressor){ + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_LabeledStatement, function(self, compressor){ + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; + }); + + OPT(AST_Block, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + return self; + }); + + OPT(AST_BlockStatement, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: return self.body[0]; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; + }); + + AST_Scope.DEFMETHOD("drop_unused", function(compressor){ + var self = this; + if (compressor.has_directive("use asm")) return self; + var toplevel = compressor.option("toplevel"); + if (compressor.option("unused") + && (!(self instanceof AST_Toplevel) || toplevel) + && !self.uses_eval + && !self.uses_with) { + var assign_as_unused = !/keep_assign/.test(compressor.option("unused")); + var drop_funcs = /funcs/.test(toplevel); + var drop_vars = /vars/.test(toplevel); + if (!(self instanceof AST_Toplevel) || toplevel == true) { + drop_funcs = drop_vars = true; + } + var in_use = []; + var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.each(function(def) { + if (compressor.top_retain(def) && !(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + }); + } + var initializations = new Dictionary(); + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend){ + if (node !== self) { + if (node instanceof AST_Defun) { + if (!drop_funcs && scope === self) { + var node_def = node.name.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + initializations.add(node.name.name, node); + return true; // don't go in nested scopes + } + if (node instanceof AST_Definitions && scope === self) { + node.definitions.forEach(function(def){ + if (!drop_vars) { + var node_def = def.name.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + if (def.value) { + initializations.add(def.name.name, def.value); + if (def.value.has_side_effects(compressor)) { + def.value.walk(tw); + } + } + }); + return true; + } + if (assign_as_unused + && node instanceof AST_Assign + && node.operator == "=" + && node.left instanceof AST_SymbolRef + && !is_reference_const(node.left) + && scope === self) { + node.right.walk(tw); + return true; + } + if (node instanceof AST_SymbolRef) { + var node_def = node.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + return true; + } + if (node instanceof AST_Scope) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + for (var i = 0; i < in_use.length; ++i) { + in_use[i].orig.forEach(function(decl){ + // undeclared globals will be instanceof AST_SymbolRef + var init = initializations.get(decl.name); + if (init) init.forEach(function(init){ + var tw = new TreeWalker(function(node){ + if (node instanceof AST_SymbolRef) { + var node_def = node.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + }); + init.walk(tw); + }); + }); + } + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + if (node instanceof AST_Function + && node.name + && !compressor.option("keep_fnames")) { + var def = node.name.definition(); + // any declarations with same name will overshadow + // name of this anonymous function and can therefore + // never be used anywhere + if (!(def.id in in_use_ids) || def.orig.length > 1) + node.name = null; + } + if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { + var trim = !compressor.option("keep_fargs"); + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (!(sym.definition().id in in_use_ids)) { + sym.__unused = true; + if (trim) { + a.pop(); + compressor[sym.unreferenced() ? "warn" : "info"]("Dropping unused function argument {name} [{file}:{line},{col}]", { + name : sym.name, + file : sym.start.file, + line : sym.start.line, + col : sym.start.col + }); + } + } + else { + trim = false; + } + } + } + if (drop_funcs && node instanceof AST_Defun && node !== self) { + if (!(node.name.definition().id in in_use_ids)) { + compressor[node.name.unreferenced() ? "warn" : "info"]("Dropping unused function {name} [{file}:{line},{col}]", { + name : node.name.name, + file : node.name.start.file, + line : node.name.start.line, + col : node.name.start.col + }); + return make_node(AST_EmptyStatement, node); + } + return node; + } + if (drop_vars && node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn && tt.parent().init === node)) { + var def = node.definitions.filter(function(def){ + if (def.value) def.value = def.value.transform(tt); + var sym = def.name.definition(); + if (sym.id in in_use_ids) return true; + if (sym.orig[0] instanceof AST_SymbolCatch) { + def.value = def.value && def.value.drop_side_effect_free(compressor); + return true; + } + var w = { + name : def.name.name, + file : def.name.start.file, + line : def.name.start.line, + col : def.name.start.col + }; + if (def.value && (def._unused_side_effects = def.value.drop_side_effect_free(compressor))) { + compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); + return true; + } + compressor[def.name.unreferenced() ? "warn" : "info"]("Dropping unused variable {name} [{file}:{line},{col}]", w); + return false; + }); + // place uninitialized names at the start + def = mergeSort(def, function(a, b){ + if (!a.value && b.value) return -1; + if (!b.value && a.value) return 1; + return 0; + }); + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + for (var i = 0; i < def.length;) { + var x = def[i]; + if (x._unused_side_effects) { + side_effects.push(x._unused_side_effects); + def.splice(i, 1); + } else { + if (side_effects.length > 0) { + side_effects.push(x.value); + x.value = AST_Seq.from_array(side_effects); + side_effects = []; + } + ++i; + } + } + if (side_effects.length > 0) { + side_effects = make_node(AST_BlockStatement, node, { + body: [ make_node(AST_SimpleStatement, node, { + body: AST_Seq.from_array(side_effects) + }) ] + }); + } else { + side_effects = null; + } + if (def.length == 0 && !side_effects) { + return make_node(AST_EmptyStatement, node); + } + if (def.length == 0) { + return in_list ? MAP.splice(side_effects.body) : side_effects; + } + node.definitions = def; + if (side_effects) { + side_effects.body.unshift(node); + return in_list ? MAP.splice(side_effects.body) : side_effects; + } + return node; + } + if (drop_vars && assign_as_unused + && node instanceof AST_Assign + && node.operator == "=" + && node.left instanceof AST_SymbolRef) { + var def = node.left.definition(); + if (!(def.id in in_use_ids) + && self.variables.get(def.name) === def) { + return maintain_this_binding(tt.parent(), node, node.right.transform(tt)); + } + } + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // https://github.com/mishoo/UglifyJS2/issues/1830 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + if (node instanceof AST_For) { + descend(node, this); + if (node.init instanceof AST_BlockStatement) { + var block = node.init; + node.init = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } else if (is_empty(node.init)) { + node.init = null; + } + return node; + } + if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) { + descend(node, this); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_Scope && node !== self) + return node; + } + ); + self.transform(tt); + } + }); + + AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ + var self = this; + if (compressor.has_directive("use asm")) return self; + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Dictionary(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + })); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Defun && hoist_funs) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Var && hoist_vars) { + node.definitions.forEach(function(def){ + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(compressor); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) { + var def = node.definitions[0].name; + return make_node(AST_SymbolRef, def, def); + } + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + vars.each(function(def, name){ + if (self instanceof AST_Lambda + && find_if(function(x){ return x.name == def.name.name }, + self.argnames)) { + vars.del(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Seq + && (assign = expr.car) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = expr.cdr; + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + var tmp = [ i, 1 ].concat(self.body[i].body); + self.body.splice.apply(self.body, tmp); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + }; + } + self.body = dirs.concat(hoisted, self.body); + } + return self; + }); + + // drop_side_effect_free() + // remove side-effect-free parts which only affects return value + (function(def){ + // Drop side-effect-free elements from an array of expressions. + // Returns an array of expressions with side-effects or null + // if all elements were dropped. Note: original array may be + // returned if nothing changed. + function trim(nodes, compressor, first_in_statement) { + var ret = [], changed = false; + for (var i = 0, len = nodes.length; i < len; i++) { + var node = nodes[i].drop_side_effect_free(compressor, first_in_statement); + changed |= node !== nodes[i]; + if (node) { + ret.push(node); + first_in_statement = false; + } + } + return changed ? ret.length ? ret : null : nodes; + } + + def(AST_Node, return_this); + def(AST_Constant, return_null); + def(AST_This, return_null); + def(AST_Call, function(compressor, first_in_statement){ + if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) { + if (this.expression instanceof AST_Function + && (!this.expression.name || !this.expression.name.definition().references.length)) { + var node = this.clone(); + node.expression = node.expression.process_expression(false, compressor); + return node; + } + return this; + } + if (this.pure) { + compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]", this.start); + this.pure.value = this.pure.value.replace(/[@#]__PURE__/g, ' '); + } + var args = trim(this.args, compressor, first_in_statement); + return args && AST_Seq.from_array(args); + }); + def(AST_Accessor, return_null); + def(AST_Function, return_null); + def(AST_Binary, function(compressor, first_in_statement){ + var right = this.right.drop_side_effect_free(compressor); + if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement); + switch (this.operator) { + case "&&": + case "||": + if (right === this.right) return this; + var node = this.clone(); + node.right = right; + return node; + default: + var left = this.left.drop_side_effect_free(compressor, first_in_statement); + if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement); + return make_node(AST_Seq, this, { + car: left, + cdr: right + }); + } + }); + def(AST_Assign, return_this); + def(AST_Conditional, function(compressor){ + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) return this; + if (!consequent) return alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative + }) : this.condition.drop_side_effect_free(compressor); + if (!alternative) return make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent + }); + var node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + return node; + }); + def(AST_Unary, function(compressor, first_in_statement){ + if (unary_side_effects(this.operator)) return this; + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement + && this instanceof AST_UnaryPrefix + && is_iife_call(expression)) { + if (expression === this.expression && this.operator.length === 1) return this; + return make_node(AST_UnaryPrefix, this, { + operator: this.operator.length === 1 ? this.operator : "!", + expression: expression + }); + } + return expression; + }); + def(AST_SymbolRef, function() { + return this.undeclared() ? this : null; + }); + def(AST_Object, function(compressor, first_in_statement){ + var values = trim(this.properties, compressor, first_in_statement); + return values && AST_Seq.from_array(values); + }); + def(AST_ObjectProperty, function(compressor, first_in_statement){ + return this.value.drop_side_effect_free(compressor, first_in_statement); + }); + def(AST_Array, function(compressor, first_in_statement){ + var values = trim(this.elements, compressor, first_in_statement); + return values && AST_Seq.from_array(values); + }); + def(AST_Dot, function(compressor, first_in_statement){ + if (this.expression.may_throw_on_access(compressor)) return this; + return this.expression.drop_side_effect_free(compressor, first_in_statement); + }); + def(AST_Sub, function(compressor, first_in_statement){ + if (this.expression.may_throw_on_access(compressor)) return this; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement); + var property = this.property.drop_side_effect_free(compressor); + if (!property) return expression; + return make_node(AST_Seq, this, { + car: expression, + cdr: property + }); + }); + def(AST_Seq, function(compressor){ + var cdr = this.cdr.drop_side_effect_free(compressor); + if (cdr === this.cdr) return this; + if (!cdr) return this.car; + return make_node(AST_Seq, this, { + car: this.car, + cdr: cdr + }); + }); + })(function(node, func){ + node.DEFMETHOD("drop_side_effect_free", func); + }); + + OPT(AST_SimpleStatement, function(self, compressor){ + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; + }); + + OPT(AST_DWLoop, function(self, compressor){ + if (!compressor.option("loops")) return self; + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return make_node(AST_For, self, { + body: self.body + }); + } + if (compressor.option("dead_code") && self instanceof AST_While) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + if (self instanceof AST_Do) { + var has_loop_control = false; + var tw = new TreeWalker(function(node) { + if (node instanceof AST_Scope || has_loop_control) return true; + if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === self) + return has_loop_control = true; + }); + var parent = compressor.parent(); + (parent instanceof AST_LabeledStatement ? parent : self).walk(tw); + if (!has_loop_control) return self.body; + } + } + if (self instanceof AST_While) { + return make_node(AST_For, self, self).optimize(compressor); + } + return self; + }); + + function if_break_in_loop(self, compressor) { + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + if_break_in_loop(self, compressor); + } + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (first instanceof AST_If) { + if (first.body instanceof AST_Break + && compressor.loopcontrol_target(first.body) === compressor.self()) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } + else if (first.alternative instanceof AST_Break + && compressor.loopcontrol_target(first.alternative) === compressor.self()) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + }; + + OPT(AST_For, function(self, compressor){ + if (!compressor.option("loops")) return self; + if (self.condition) { + var cond = self.condition.evaluate(compressor); + if (compressor.option("dead_code") && !cond) { + var a = []; + if (self.init instanceof AST_Statement) { + a.push(self.init); + } + else if (self.init) { + a.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + if (cond !== self.condition) { + cond = make_node_from_constant(cond, self.condition).transform(compressor); + self.condition = best_of_expression(cond, self.condition); + } + } + if_break_in_loop(self, compressor); + return self; + }); + + OPT(AST_If, function(self, compressor){ + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, warn and drop + // one of the blocks. note, statically determined implies + // “has no side effectsâ€; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + if (self.alternative) { + extract_declarations_from_unreachable_code(compressor, self.alternative, a); + } + a.push(self.body); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + if (self.alternative) a.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + } + cond = make_node_from_constant(cond, self.condition).transform(compressor); + self.condition = best_of_expression(cond, self.condition); + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.print_to_string().length; + var negated_length = negated.print_to_string().length; + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement, self); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition.clone() + }).optimize(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).optimize(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS2/issues/979 + negated_is_best = true; + } + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).optimize(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative) + }).transform(compressor) + }).optimize(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }), + body: self.body.body, + alternative: null + }); + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).optimize(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).optimize(compressor); + } + return self; + }); + + OPT(AST_Switch, function(self, compressor){ + if (!compressor.option("switches")) return self; + var branch; + var value = self.expression.evaluate(compressor); + if (value !== self.expression) { + var expression = make_node_from_constant(value, self.expression).transform(compressor); + self.expression = best_of_expression(expression, self.expression); + } + if (!compressor.option("dead_code")) return self; + var decl = []; + var body = []; + var default_branch; + var exact_match; + for (var i = 0, len = self.body.length; i < len && !exact_match; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + if (!default_branch) { + default_branch = branch; + } else { + eliminate_branch(branch, body[body.length - 1]); + } + } else if (value !== self.expression) { + var exp = branch.expression.evaluate(compressor); + if (exp === value) { + exact_match = branch; + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + } else if (exp !== branch.expression) { + eliminate_branch(branch, body[body.length - 1]); + continue; + } + } + if (aborts(branch)) { + var prev = body[body.length - 1]; + if (aborts(prev) && prev.body.length == branch.body.length + && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) { + prev.body = []; + } + } + body.push(branch); + } + while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]); + if (body.length > 0) { + body[0].body = decl.concat(body[0].body); + } + self.body = body; + while (branch = body[body.length - 1]) { + var stat = branch.body[branch.body.length - 1]; + if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self) + branch.body.pop(); + if (branch.body.length || branch instanceof AST_Case + && (default_branch || branch.expression.has_side_effects(compressor))) break; + if (body.pop() === default_branch) default_branch = null; + } + if (body.length == 0) { + return make_node(AST_BlockStatement, self, { + body: decl.concat(make_node(AST_SimpleStatement, self.expression, { + body: self.expression + })) + }).optimize(compressor); + } + if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) { + var has_break = false; + var tw = new TreeWalker(function(node) { + if (has_break + || node instanceof AST_Lambda + || node instanceof AST_SimpleStatement) return true; + if (node instanceof AST_Break && tw.loopcontrol_target(node) === self) + has_break = true; + }); + self.walk(tw); + if (!has_break) { + body = body[0].body.slice(); + body.unshift(make_node(AST_SimpleStatement, self.expression, { + body: self.expression + })); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + } + return self; + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + extract_declarations_from_unreachable_code(compressor, branch, decl); + } + } + }); + + OPT(AST_Try, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + if (self.bcatch && self.bfinally && all(self.bfinally.body, is_empty)) self.bfinally = null; + if (all(self.body, is_empty)) { + var body = []; + if (self.bcatch) extract_declarations_from_unreachable_code(compressor, self.bcatch, body); + if (self.bfinally) body = body.concat(self.bfinally.body); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + return self; + }); + + AST_Definitions.DEFMETHOD("remove_initializers", function(){ + this.definitions.forEach(function(def){ def.value = null }); + }); + + AST_Definitions.DEFMETHOD("to_assignments", function(compressor){ + var reduce_vars = compressor.option("reduce_vars"); + var assignments = this.definitions.reduce(function(a, def){ + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + a.push(make_node(AST_Assign, def, { + operator : "=", + left : name, + right : def.value + })); + if (reduce_vars) name.definition().fixed = false; + } + return a; + }, []); + if (assignments.length == 0) return null; + return AST_Seq.from_array(assignments); + }); + + OPT(AST_Definitions, function(self, compressor){ + if (self.definitions.length == 0) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_Call, function(self, compressor){ + var exp = self.expression; + if (compressor.option("reduce_vars") + && exp instanceof AST_SymbolRef) { + var def = exp.definition(); + var fixed = exp.fixed_value(); + if (fixed instanceof AST_Defun) { + def.fixed = fixed = make_node(AST_Function, fixed, fixed).clone(true); + } + if (fixed instanceof AST_Function) { + exp = fixed; + if (compressor.option("unused") + && def.references.length == 1 + && !(def.scope.uses_arguments + && def.orig[0] instanceof AST_SymbolFunarg) + && !def.scope.uses_eval + && compressor.find_parent(AST_Scope) === def.scope) { + self.expression = exp; + } + } + } + if (compressor.option("unused") + && exp instanceof AST_Function + && !exp.uses_arguments + && !exp.uses_eval) { + var pos = 0, last = 0; + for (var i = 0, len = self.args.length; i < len; i++) { + var trim = i >= exp.argnames.length; + if (trim || exp.argnames[i].__unused) { + var node = self.args[i].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } else if (!trim) { + self.args[pos++] = make_node(AST_Number, self.args[i], { + value: 0 + }); + continue; + } + } else { + self.args[pos++] = self.args[i]; + } + last = pos; + } + self.args.length = last; + } + if (compressor.option("unsafe")) { + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }).optimize(compressor); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + if (self.args.length <= 1) return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }).optimize(compressor); + break; + case "Number": + if (self.args.length == 0) return make_node(AST_Number, self, { + value: 0 + }); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "+" + }).optimize(compressor); + case "Boolean": + if (self.args.length == 0) return make_node(AST_False, self); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "!" + }), + operator: "!" + }).optimize(compressor); + break; + case "Function": + // new Function() => function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [] + }); + if (all(self.args, function(x){ return x instanceof AST_String })) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS2/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "(function(" + self.args.slice(0, -1).map(function(arg){ + return arg.value; + }).join(",") + "){" + self.args[self.args.length - 1].value + "})()"; + var ast = parse(code); + ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); + var comp = new Compressor(compressor.options); + ast = ast.transform(comp); + ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); + ast.mangle_names(); + var fun; + try { + ast.walk(new TreeWalker(function(node){ + if (node instanceof AST_Lambda) { + fun = node; + throw ast; + } + })); + } catch(ex) { + if (ex !== ast) throw ex; + }; + if (!fun) return self; + var args = fun.argnames.map(function(arg, i){ + return make_node(AST_String, self.args[i], { + value: arg.print_to_string() + }); + }); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, fun, code); + code = code.toString().replace(/^\{|\}$/g, ""); + args.push(make_node(AST_String, self.args[self.args.length - 1], { + value: code + })); + self.args = args; + return self; + } catch(ex) { + if (ex instanceof JS_Parse_Error) { + compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start); + compressor.warn(ex.toString()); + } else { + console.log(ex); + throw ex; + } + } + } + break; + } + } + else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).optimize(compressor); + } + else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: { + var separator; + if (self.args.length > 0) { + separator = self.args[0].evaluate(compressor); + if (separator === self.args[0]) break EXIT; // not a constant + } + var elements = []; + var consts = []; + exp.expression.elements.forEach(function(el) { + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + consts.length = 0; + } + elements.push(el); + } + }); + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + } + if (elements.length == 0) return make_node(AST_String, self, { value: "" }); + if (elements.length == 1) { + if (elements[0].is_string(compressor)) { + return elements[0]; + } + return make_node(AST_Binary, elements[0], { + operator : "+", + left : make_node(AST_String, self, { value: "" }), + right : elements[0] + }); + } + if (separator == "") { + var first; + if (elements[0].is_string(compressor) + || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el){ + return make_node(AST_Binary, el, { + operator : "+", + left : prev, + right : el + }); + }, first).optimize(compressor); + } + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + else if (exp instanceof AST_Dot && exp.expression.is_string(compressor) && exp.property == "charAt") { + var arg = self.args[0]; + var index = arg ? arg.evaluate(compressor) : 0; + if (index !== arg) { + return make_node(AST_Sub, exp, { + expression: exp.expression, + property: make_node_from_constant(index | 0, arg || exp) + }).optimize(compressor); + } + } + } + if (exp instanceof AST_Function) { + if (exp.body[0] instanceof AST_Return) { + var value = exp.body[0].value; + if (!value || value.is_constant()) { + var args = self.args.concat(value || make_node(AST_Undefined, self)); + return AST_Seq.from_array(args).transform(compressor); + } + } + if (compressor.option("side_effects") && all(exp.body, is_empty)) { + var args = self.args.concat(make_node(AST_Undefined, self)); + return AST_Seq.from_array(args).transform(compressor); + } + } + if (compressor.option("drop_console")) { + if (exp instanceof AST_PropAccess) { + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (name instanceof AST_SymbolRef + && name.name == "console" + && name.undeclared()) { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + } + if (compressor.option("negate_iife") + && compressor.parent() instanceof AST_SimpleStatement + && is_iife_call(self)) { + return self.negate(compressor, true); + } + return self; + }); + + OPT(AST_New, function(self, compressor){ + if (compressor.option("unsafe")) { + var exp = self.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Object": + case "RegExp": + case "Function": + case "Error": + case "Array": + return make_node(AST_Call, self, self).transform(compressor); + } + } + } + return self; + }); + + OPT(AST_Seq, function(self, compressor){ + if (!compressor.option("side_effects")) + return self; + self.car = self.car.drop_side_effect_free(compressor, first_in_statement(compressor)); + if (!self.car) return maintain_this_binding(compressor.parent(), self, self.cdr); + if (compressor.option("cascade")) { + var left; + if (self.car instanceof AST_Assign + && !self.car.left.has_side_effects(compressor)) { + left = self.car.left; + } else if (self.car instanceof AST_Unary + && (self.car.operator == "++" || self.car.operator == "--")) { + left = self.car.expression; + } + if (left + && !(left instanceof AST_SymbolRef + && (left.definition().orig[0] instanceof AST_SymbolLambda + || is_reference_const(left)))) { + var parent, field; + var cdr = self.cdr; + while (true) { + if (cdr.equivalent_to(left)) { + var car = self.car instanceof AST_UnaryPostfix ? make_node(AST_UnaryPrefix, self.car, { + operator: self.car.operator, + expression: left + }) : self.car; + if (parent) { + parent[field] = car; + return self.cdr; + } + return car; + } + if (cdr instanceof AST_Binary && !(cdr instanceof AST_Assign)) { + if (cdr.left.is_constant()) { + if (cdr.operator == "||" || cdr.operator == "&&") break; + field = "right"; + } else { + field = "left"; + } + } else if (cdr instanceof AST_Call + || cdr instanceof AST_Unary && !unary_side_effects(cdr.operator)) { + field = "expression"; + } else break; + parent = cdr; + cdr = cdr[field]; + } + } + } + if (is_undefined(self.cdr, compressor)) { + return make_node(AST_UnaryPrefix, self, { + operator : "void", + expression : self.car + }); + } + return self; + }); + + AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Seq) { + var seq = this.expression; + var x = seq.to_array(); + var e = this.clone(); + e.expression = x.pop(); + x.push(e); + seq = AST_Seq.from_array(x).transform(compressor); + return seq; + } + } + return this; + }); + + OPT(AST_UnaryPostfix, function(self, compressor){ + return self.lift_sequences(compressor); + }); + + OPT(AST_UnaryPrefix, function(self, compressor){ + var e = self.expression; + if (self.operator == "delete" + && !(e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_NaN + || e instanceof AST_Infinity + || e instanceof AST_Undefined)) { + if (e instanceof AST_Seq) { + e = e.to_array(); + e.push(make_node(AST_True, self)); + return AST_Seq.from_array(e).optimize(compressor); + } + return make_node(AST_Seq, self, { + car: e, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + var seq = self.lift_sequences(compressor); + if (seq !== self) { + return seq; + } + if (compressor.option("side_effects") && self.operator == "void") { + e = e.drop_side_effect_free(compressor); + if (e) { + self.expression = e; + return self; + } else { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + if (e instanceof AST_Binary) { + self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor))); + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); + return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_node(AST_Seq, self, { + car: e, + cdr: make_node(AST_True, self) + })).optimize(compressor); + } + } + if (self.operator == "-" && e instanceof AST_Infinity) { + e = e.transform(compressor); + } + if (e instanceof AST_Binary + && (self.operator == "+" || self.operator == "-") + && (e.operator == "*" || e.operator == "/" || e.operator == "%")) { + return make_node(AST_Binary, self, { + operator: e.operator, + left: make_node(AST_UnaryPrefix, e.left, { + operator: self.operator, + expression: e.left + }), + right: e.right + }); + } + // avoids infinite recursion of numerals + if (self.operator != "-" + || !(e instanceof AST_Number || e instanceof AST_Infinity)) { + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + } + return self; + }); + + AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.left instanceof AST_Seq) { + var seq = this.left; + var x = seq.to_array(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return AST_Seq.from_array(x).optimize(compressor); + } + if (this.right instanceof AST_Seq && !this.left.has_side_effects(compressor)) { + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var root = this.right.clone(); + var cursor, seq = root; + while (assign || !seq.car.has_side_effects(compressor)) { + cursor = seq; + if (seq.cdr instanceof AST_Seq) { + seq = seq.cdr = seq.cdr.clone(); + } else break; + } + if (cursor) { + var e = this.clone(); + e.right = cursor.cdr; + cursor.cdr = e; + return root.optimize(compressor); + } + } + } + return this; + }); + + var commutativeOperators = makePredicate("== === != !== * & | ^"); + + OPT(AST_Binary, function(self, compressor){ + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + if (commutativeOperators(self.operator)) { + if (self.right.is_constant() + && !self.left.is_constant()) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + + if (!(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + reverse(); + } + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean() && self.right.is_boolean())) { + self.operator = self.operator.substr(0, 2); + } + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // "undefined" == typeof x => undefined === x + if (self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? !expr.undeclared() + : !(expr instanceof AST_PropAccess) || compressor.option("screw_ie8")) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } + break; + } + if (compressor.option("booleans") && self.operator == "+" && compressor.in_boolean_context()) { + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if (ll && typeof ll == "string") { + compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.right, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + if (rr && typeof rr == "string") { + compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + } + if (compressor.option("comparisons") && self.is_boolean()) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor, first_in_statement(compressor)) + }); + self = best_of(compressor, self, negated); + } + if (compressor.option("unsafe_comps")) { + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + } + if (self.operator == "+") { + if (self.right instanceof AST_String + && self.right.getValue() == "" + && self.left.is_string(compressor)) { + return self.left; + } + if (self.left instanceof AST_String + && self.left.getValue() == "" + && self.right.is_string(compressor)) { + return self.right; + } + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.getValue() == "" + && self.right.is_string(compressor)) { + self.left = self.left.right; + return self.transform(compressor); + } + } + if (compressor.option("evaluate")) { + switch (self.operator) { + case "&&": + var ll = self.left.evaluate(compressor); + if (!ll) { + compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor); + } else if (ll !== self.left) { + compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor); + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + var rr = self.right.evaluate(compressor); + if (!rr) { + compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_False, self) + }).optimize(compressor); + } else if (rr !== self.right) { + compressor.warn("Dropping side-effect-free && in boolean context [{file}:{line},{col}]", self.start); + return self.left.optimize(compressor); + } + } + break; + case "||": + var ll = self.left.evaluate(compressor); + if (!ll) { + compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor); + } else if (ll !== self.left) { + compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor); + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + var rr = self.right.evaluate(compressor); + if (!rr) { + compressor.warn("Dropping side-effect-free || in boolean context [{file}:{line},{col}]", self.start); + return self.left.optimize(compressor); + } else if (rr !== self.right) { + compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + } + break; + } + var associative = true; + switch (self.operator) { + case "+": + // "foo" + ("bar" + x) => "foobar" + x + if (self.left instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.left instanceof AST_Constant + && self.right.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self.left, { + value: "" + self.left.getValue() + self.right.left.getValue(), + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.right instanceof AST_Constant + && self.left.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: make_node(AST_String, self.right, { + value: "" + self.left.right.getValue() + self.right.getValue(), + start: self.left.right.start, + end: self.right.end + }) + }); + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.left instanceof AST_Constant + && self.right.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: make_node(AST_String, self.left.right, { + value: "" + self.left.right.getValue() + self.right.left.getValue(), + start: self.left.right.start, + end: self.right.left.end + }) + }), + right: self.right.right + }); + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (self.operator == "&&" + || self.operator == "||" + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor)))))) + { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left, + right : self.right.left + }); + self.right = self.right.right; + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + OPT(AST_SymbolRef, function(self, compressor){ + var def = self.resolve_defines(compressor); + if (def) { + return def.optimize(compressor); + } + // testing against !self.scope.uses_with first is an optimization + if (compressor.option("screw_ie8") + && self.undeclared() + && (!self.scope.uses_with || !compressor.find_parent(AST_With))) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + if (compressor.option("evaluate") + && compressor.option("reduce_vars") + && is_lhs(self, compressor.parent()) !== self) { + var d = self.definition(); + var fixed = self.fixed_value(); + if (fixed) { + if (d.should_replace === undefined) { + var init = fixed.evaluate(compressor); + if (init !== fixed && (compressor.option("unsafe_regexp") || !(init instanceof RegExp))) { + init = make_node_from_constant(init, fixed); + var value = init.optimize(compressor).print_to_string().length; + var fn; + if (has_symbol_ref(fixed)) { + fn = function() { + var result = init.optimize(compressor); + return result === init ? result.clone(true) : result; + }; + } else { + value = Math.min(value, fixed.print_to_string().length); + fn = function() { + var result = best_of_expression(init.optimize(compressor), fixed); + return result === init || result === fixed ? result.clone(true) : result; + }; + } + var name = d.name.length; + var overhead = 0; + if (compressor.option("unused") && (!d.global || compressor.option("toplevel"))) { + overhead = (name + 2 + value) / d.references.length; + } + d.should_replace = value <= name + overhead ? fn : false; + } else { + d.should_replace = false; + } + } + if (d.should_replace) { + return d.should_replace(); + } + } + } + return self; + + function has_symbol_ref(value) { + var found; + value.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) found = true; + if (found) return true; + })); + return found; + } + }); + + function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; + } + + OPT(AST_Undefined, function(self, compressor){ + if (compressor.option("unsafe")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + ref.is_undefined = true; + return ref; + } + } + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); + }); + + OPT(AST_Infinity, function(self, compressor){ + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if (compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity")) + return self; + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + }); + + OPT(AST_NaN, function(self, compressor){ + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; + }); + + var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; + var ASSIGN_OPS_COMMUTATIVE = [ '*', '|', '^', '&' ]; + OPT(AST_Assign, function(self, compressor){ + self = self.lift_sequences(compressor); + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && member(self.right.operator, ASSIGN_OPS)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } + else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && member(self.right.operator, ASSIGN_OPS_COMMUTATIVE) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + }); + + OPT(AST_Conditional, function(self, compressor){ + if (!compressor.option("conditionals")) return self; + if (self.condition instanceof AST_Seq) { + var car = self.condition.car; + self.condition = self.condition.cdr; + return AST_Seq.cons(car, self); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.consequent); + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if (consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator == alternative.operator + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor))) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length == 1 + && alternative.args.length == 1 + && consequent.expression.equivalent_to(alternative.expression) + && !consequent.expression.has_side_effects(compressor)) { + consequent.args[0] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[0], + alternative: alternative.args[0] + }); + return consequent; + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_node(AST_Seq, self, { + car: self.condition, + cdr: consequent + }).optimize(compressor); + } + + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.value); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !!node.expression.value); + } + }); + + OPT(AST_Boolean, function(self, compressor){ + if (compressor.option("booleans")) { + var p = compressor.parent(); + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { + operator : p.operator, + value : self.value, + file : p.start.file, + line : p.start.line, + col : p.start.col, + }); + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; + }); + + OPT(AST_Sub, function(self, compressor){ + var prop = self.property; + if (prop instanceof AST_String && compressor.option("properties")) { + prop = prop.getValue(); + if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) { + return make_node(AST_Dot, self, { + expression : self.expression, + property : prop + }).optimize(compressor); + } + var v = parseFloat(prop); + if (!isNaN(v) && v.toString() == prop) { + self.property = make_node(AST_Number, self.property, { + value: v + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + OPT(AST_Dot, function(self, compressor){ + var def = self.resolve_defines(compressor); + if (def) { + return def.optimize(compressor); + } + var prop = self.property; + if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) { + return make_node(AST_Sub, self, { + expression : self.expression, + property : make_node(AST_String, self, { + value: prop + }) + }).optimize(compressor); + } + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + function literals_in_boolean_context(self, compressor) { + if (compressor.option("booleans") && compressor.in_boolean_context()) { + return best_of(compressor, self, make_node(AST_Seq, self, { + car: self, + cdr: make_node(AST_True, self) + }).optimize(compressor)); + } + return self; + }; + OPT(AST_Array, literals_in_boolean_context); + OPT(AST_Object, literals_in_boolean_context); + OPT(AST_RegExp, literals_in_boolean_context); + + OPT(AST_Return, function(self, compressor){ + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; + }); + + OPT(AST_VarDef, function(self, compressor){ + var defines = compressor.option("global_defs"); + if (defines && HOP(defines, self.name.name)) { + compressor.warn('global_defs ' + self.name.name + ' redefined [{file}:{line},{col}]', self.start); + } + return self; + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +// a small wrapper around fitzgen's source-map library +function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + + orig_line_diff : 0, + dest_line_diff : 0, + }); + var generator = new MOZ_SourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); + + if (orig_map && Array.isArray(options.orig.sources)) { + orig_map._sources.toArray().forEach(function(source) { + var sourceContent = orig_map.sourceContentFor(source, true); + if (sourceContent) { + generator.setSourceContent(source, sourceContent); + } + }); + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : { line: gen_line + options.dest_line_diff, column: gen_col }, + original : { line: orig_line + options.orig_line_diff, column: orig_col }, + source : source, + name : name + }); + }; + return { + add : add, + get : function() { return generator }, + toString : function() { return JSON.stringify(generator.toJSON()); } + }; +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +(function(){ + + var normalize_directives = function(body) { + var in_directive = true; + + for (var i = 0; i < body.length; i++) { + if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) { + in_directive = false; + } + } + + return body; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + body: normalize_directives(from_moz(M.body).body) + }); + }, + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + body: normalize_directives(from_moz(M.body).body) + }); + }, + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.kind == "init") return new AST_ObjectKeyVal(args); + args.key = new AST_SymbolAccessor({ + name: args.key + }); + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + }, + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem){ + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop){ + prop.type = "Property"; + return from_moz(prop) + }) + }); + }, + SequenceExpression: function(M) { + return AST_Seq.from_array(M.expressions.map(from_moz)); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object) + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + default: + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = new RegExp(rx.pattern, rx.flags).toString(); + } else { + // support legacy RegExp + args.value = M.regex && M.raw ? M.raw : val; + } + return new AST_RegExp(args); + } + }, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("DebuggerStatement", AST_Debugger); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("ThisExpression", AST_This); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, arguments@args"); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + body: to_moz_scope("BlockStatement", M) + } + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) { + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + body: to_moz_scope("BlockStatement", M) + } + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value + } + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: M instanceof AST_Const ? "const" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.to_array().map(to_moz) + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property} + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression", + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { + var key = { + type: "Literal", + value: M.key instanceof AST_SymbolAccessor ? M.key.name : M.key + }; + var kind; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + return { + type: "Property", + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M) { + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: value.toString(), + regex: { + pattern: value.source, + flags: value.toString().match(/[gimuy]*$/)[0] + } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) { + return { + type: "UnaryExpression", + operator: "-", + prefix: true, + argument: { + type: "Literal", + value: -value, + raw: M.start.raw + } + }; + } + return { + type: "Literal", + value: value, + raw: M.start.raw + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function raw_token(moznode) { + if (moznode.type == "Literal") { + return moznode.raw != null ? moznode.raw : moznode.value + ""; + } + } + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : start && start.line, + col : start && start.column, + pos : range ? range[0] : moznode.start, + endline : start && start.line, + endcol : start && start.column, + endpos : range ? range[0] : moznode.start, + raw : raw_token(moznode), + }); + }; + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : end && end.line, + col : end && end.column, + pos : range ? range[1] : moznode.end, + endline : end && end.line, + endcol : end && end.column, + endpos : range ? range[1] : moznode.end, + raw : raw_token(moznode), + }); + }; + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new U2." + mytype.name + "({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; + me_to_moz += "return {\n" + + "type: " + JSON.stringify(moztype); + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ + var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + me_to_moz += ",\n" + moz + ": "; + switch (how) { + case "@": + moz_to_me += "M." + moz + ".map(from_moz)"; + me_to_moz += "M." + my + ".map(to_moz)"; + break; + case ">": + moz_to_me += "from_moz(M." + moz + ")"; + me_to_moz += "to_moz(M." + my + ")"; + break; + case "=": + moz_to_me += "M." + moz; + me_to_moz += "M." + my; + break; + case "%": + moz_to_me += "from_moz(M." + moz + ").body"; + me_to_moz += "to_moz_block(M)"; + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + moz_to_me += "\n})\n}"; + me_to_moz += "\n}\n}"; + + //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); + //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true }); + //console.log(moz_to_me); + + moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + exports, my_start_token, my_end_token, from_moz + ); + me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")( + to_moz, to_moz_block, to_moz_scope + ); + MOZ_TO_ME[moztype] = moz_to_me; + def_to_moz(mytype, me_to_moz); + }; + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + }; + + AST_Node.from_mozilla_ast = function(node){ + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode, myparent) { + var start = mynode.start; + var end = mynode.end; + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + }; + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function() { + return set_moz_loc(this, handler(this)); + }); + }; + + function to_moz(node) { + return node != null ? node.to_mozilla_ast() : null; + }; + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + }; + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + }; +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function find_builtins() { + // NaN will be included due to Number.NaN + var a = [ + "null", + "true", + "false", + "Infinity", + "-Infinity", + "undefined", + ]; + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp + ].forEach(function(ctor){ + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + push_uniq(a, name); + } + return a; +} + +function mangle_properties(ast, options) { + options = defaults(options, { + cache: null, + debug: false, + ignore_quoted: false, + only_cache: false, + regex: null, + reserved: null, + }); + + var reserved = options.reserved; + if (reserved == null) + reserved = find_builtins(); + + var cache = options.cache; + if (cache == null) { + cache = { + cname: -1, + props: new Dictionary() + }; + } + + var regex = options.regex; + var ignore_quoted = options.ignore_quoted; + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = (options.debug !== false); + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = []; + var unmangleable = []; + var ignored = {}; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node){ + if (node instanceof AST_ObjectKeyVal) { + add(node.key, ignore_quoted && node.quote); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + add(node.key.name); + } + else if (node instanceof AST_Dot) { + add(node.property); + } + else if (node instanceof AST_Sub) { + addStrings(node.property, ignore_quoted); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node){ + if (node instanceof AST_ObjectKeyVal) { + if (!(ignore_quoted && node.quote)) + node.key = mangle(node.key); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter + node.key.name = mangle(node.key.name); + } + else if (node instanceof AST_Dot) { + node.property = mangle(node.property); + } + else if (node instanceof AST_Sub) { + if (!ignore_quoted) + node.property = mangleStrings(node.property); + } + // else if (node instanceof AST_String) { + // if (should_mangle(node.value)) { + // AST_Node.warn( + // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", { + // file : node.start.file, + // line : node.start.line, + // col : node.start.col, + // prop : node.value + // } + // ); + // } + // } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.indexOf(name) >= 0) return false; + if (reserved.indexOf(name) >= 0) return false; + if (options.only_cache) { + return cache.props.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (ignore_quoted && name in ignored) return false; + if (regex && !regex.test(name)) return false; + if (reserved.indexOf(name) >= 0) return false; + return cache.props.has(name) + || names_to_mangle.indexOf(name) >= 0; + } + + function add(name, ignore) { + if (ignore) { + ignored[name] = true; + return; + } + + if (can_mangle(name)) + push_uniq(names_to_mangle, name); + + if (!should_mangle(name)) { + push_uniq(unmangleable, name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.props.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled) && !(ignore_quoted && debug_mangled in ignored)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + // note can_mangle() does not check if the name collides with the 'ignored' set + // (filled with quoted properties when ignore_quoted set). Make sure we add this + // check so we don't collide with a quoted name. + do { + mangled = base54(++cache.cname); + } while (!can_mangle(mangled) || (ignore_quoted && mangled in ignored)); + } + + cache.props.set(name, mangled); + } + return mangled; + } + + function addStrings(node, ignore) { + var out = {}; + try { + (function walk(node){ + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Seq) { + walk(node.cdr); + return true; + } + if (node instanceof AST_String) { + add(node.value, ignore); + return true; + } + if (node instanceof AST_Conditional) { + walk(node.consequent); + walk(node.alternative); + return true; + } + throw out; + })); + })(node); + } catch(ex) { + if (ex !== out) throw ex; + } + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node){ + if (node instanceof AST_Seq) { + node.cdr = mangleStrings(node.cdr); + } + else if (node instanceof AST_String) { + node.value = mangle(node.value); + } + else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } + +} + +exports["Compressor"] = Compressor; +exports["DefaultsError"] = DefaultsError; +exports["Dictionary"] = Dictionary; +exports["JS_Parse_Error"] = JS_Parse_Error; +exports["MAP"] = MAP; +exports["OutputStream"] = OutputStream; +exports["SourceMap"] = SourceMap; +exports["TreeTransformer"] = TreeTransformer; +exports["TreeWalker"] = TreeWalker; +exports["base54"] = base54; +exports["defaults"] = defaults; +exports["mangle_properties"] = mangle_properties; +exports["merge"] = merge; +exports["parse"] = parse; +exports["push_uniq"] = push_uniq; +exports["string_template"] = string_template; +exports["tokenizer"] = tokenizer; +exports["is_identifier"] = is_identifier; +exports["SymbolDef"] = SymbolDef; + +AST_Node.warn_function = function(txt) { logger.error("uglifyjs WARN: " + txt); }; +// workaround for tty output truncation upon process.exit() +[process.stdout, process.stderr].forEach(function(stream){ + if (stream._handle && stream._handle.setBlocking) + stream._handle.setBlocking(true); +}); + +exports.AST_Node.warn_function = function(txt) { + console.error("WARN: %s", txt); +}; + +function read_source_map(code) { + var match = /\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code); + if (!match) { + exports.AST_Node.warn("inline source map not found"); + return null; + } + return JSON.parse(new Buffer(match[2], "base64")); +} + +exports.minify = function(files, options, name) { + options = exports.defaults(options, { + compress : {}, + fromString : false, + inSourceMap : null, + mangle : {}, + mangleProperties : false, + nameCache : null, + outFileName : null, + output : null, + outSourceMap : null, + parse : {}, + sourceMapInline : false, + sourceMapUrl : null, + sourceRoot : null, + spidermonkey : false, + warnings : false, + }); + exports.base54.reset(); + + var inMap = options.inSourceMap; + if (typeof inMap == "string" && inMap != "inline") { + inMap = JSON.parse(rjsFile.readFile(inMap, "utf8")); + } + + // 1. parse + var toplevel = null, + sourcesContent = {}; + + if (options.spidermonkey) { + if (inMap == "inline") { + throw new Error("inline source map only works with built-in parser"); + } + toplevel = exports.AST_Node.from_mozilla_ast(files); + } else { + var addFile = function(file, fileUrl) { + var code = options.fromString + ? file + : rjsFile.readFile(file, "utf8"); + if (inMap == "inline") { + inMap = read_source_map(code); + } + sourcesContent[fileUrl] = code; + toplevel = exports.parse(code, { + filename: fileUrl, + toplevel: toplevel, + bare_returns: options.parse ? options.parse.bare_returns : undefined + }); + } + if (!options.fromString) { + files = exports.simple_glob(files); + if (inMap == "inline" && files.length > 1) { + throw new Error("inline source map only works with singular input"); + } + } + [].concat(files).forEach(function (files, i) { + if (typeof files === 'string') { + addFile(files, options.fromString ? i : files); + } else { + for (var fileUrl in files) { + addFile(files[fileUrl], fileUrl); + } + } + }); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll); + } + + // 2. compress + if (options.compress) { + var compress = { warnings: options.warnings }; + exports.merge(compress, options.compress); + toplevel.figure_out_scope(options.mangle); + var sq = exports.Compressor(compress); + toplevel = sq.compress(toplevel); + } + + // 3. mangle properties + if (options.mangleProperties || options.nameCache) { + options.mangleProperties.cache = exports.readNameCache(options.nameCache, "props"); + toplevel = exports.mangle_properties(toplevel, options.mangleProperties); + exports.writeNameCache(options.nameCache, "props", options.mangleProperties.cache); + } + + // 4. mangle + if (options.mangle) { + toplevel.figure_out_scope(options.mangle); + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + } + + // 5. output + var output = { max_line_len: 32000 }; + if (options.outSourceMap || options.sourceMapInline) { + output.source_map = exports.SourceMap({ + // prefer outFileName, otherwise use outSourceMap without .map suffix + file: options.outFileName || (typeof options.outSourceMap === 'string' ? options.outSourceMap.replace(/\.map$/i, '') : null), + orig: inMap, + root: options.sourceRoot + }); + if (options.sourceMapIncludeSources) { + for (var file in sourcesContent) { + if (sourcesContent.hasOwnProperty(file)) { + output.source_map.get().setSourceContent(file, sourcesContent[file]); + } + } + } + + } + if (options.output) { + exports.merge(output, options.output); + } + var stream = exports.OutputStream(output); + toplevel.print(stream); + + + var source_map = output.source_map; + if (source_map) { + source_map = source_map + ""; + } + + var mappingUrlPrefix = "\n//# sourceMappingURL="; + if (options.sourceMapInline) { + stream += mappingUrlPrefix + "data:application/json;charset=utf-8;base64," + new Buffer(source_map).toString("base64"); + } else if (options.outSourceMap && typeof options.outSourceMap === "string" && options.sourceMapUrl !== false) { + stream += mappingUrlPrefix + (typeof options.sourceMapUrl === "string" ? options.sourceMapUrl : options.outSourceMap); + } + + return { + code : stream + "", + map : source_map + }; +}; + +// exports.describe_ast = function() { +// function doitem(ctor) { +// var sub = {}; +// ctor.SUBCLASSES.forEach(function(ctor){ +// sub[ctor.TYPE] = doitem(ctor); +// }); +// var ret = {}; +// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; +// if (ctor.SUBCLASSES.length > 0) ret.sub = sub; +// return ret; +// } +// return doitem(exports.AST_Node).sub; +// } + +exports.describe_ast = function() { + var out = exports.OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + var props = ctor.SELF_PROPS.filter(function(prop){ + return !/^\$/.test(prop); + }); + if (props.length > 0) { + out.space(); + out.with_parens(function(){ + props.forEach(function(prop, i){ + if (i) out.space(); + out.print(prop); + }); + }); + } + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function(){ + ctor.SUBCLASSES.forEach(function(ctor, i){ + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + }; + doitem(exports.AST_Node); + return out + ""; +}; + +function readReservedFile(filename, reserved) { + if (!reserved) { + reserved = { vars: [], props: [] }; + } + var data = rjsFile.readFile(filename, "utf8"); + data = JSON.parse(data); + if (data.vars) { + data.vars.forEach(function(name){ + exports.push_uniq(reserved.vars, name); + }); + } + if (data.props) { + data.props.forEach(function(name){ + exports.push_uniq(reserved.props, name); + }); + } + return reserved; +} + +exports.readReservedFile = readReservedFile; + +exports.readDefaultReservedFile = function(reserved) { + return readReservedFile(require.resolve("./domprops.json"), reserved); +}; + +exports.readNameCache = function(filename, key) { + var cache = null; + if (filename) { + try { + var cache = rjsFile.readFile(filename, "utf8"); + cache = JSON.parse(cache)[key]; + if (!cache) throw "init"; + cache.props = exports.Dictionary.fromObject(cache.props); + } catch(ex) { + cache = { + cname: -1, + props: new exports.Dictionary() + }; + } + } + return cache; +}; + +exports.writeNameCache = function(filename, key, cache) { + if (filename) { + var data; + try { + data = rjsFile.readFile(filename, "utf8"); + data = JSON.parse(data); + } catch(ex) { + data = {}; + } + data[key] = { + cname: cache.cname, + props: cache.props.toObject() + }; + rjsFile.writeFile(filename, JSON.stringify(data, null, 2), "utf8"); + } +}; + +// A file glob function that only supports "*" and "?" wildcards in the basename. +// Example: "foo/bar/*baz??.*.js" +// Argument `glob` may be a string or an array of strings. +// Returns an array of strings. Garbage in, garbage out. +exports.simple_glob = function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob.match(/\*|\?/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; +}; + + +}); +/*jslint plusplus: true */ +/*global define: false */ + +define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) { + 'use strict'; + + function arrayToString(ary) { + var output = '['; + if (ary) { + ary.forEach(function (item, i) { + output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"'; + }); + } + output += ']'; + + return output; + } + + //This string is saved off because JSLint complains + //about obj.arguments use, as 'reserved word' + var argPropName = 'arguments', + //Default object to use for "scope" checking for UMD identifiers. + emptyScope = {}, + mixin = lang.mixin, + hasProp = lang.hasProp; + + //From an esprima example for traversing its ast. + function traverse(object, visitor) { + var child; + + if (!object) { + return; + } + + if (visitor.call(null, object) === false) { + return false; + } + for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[keys[i]]; + if (typeof child === 'object' && child !== null) { + if (traverse(child, visitor) === false) { + return false; + } + } + } + } + + //Like traverse, but visitor returning false just + //stops that subtree analysis, not the rest of tree + //visiting. + function traverseBroad(object, visitor) { + var child; + + if (!object) { + return; + } + + if (visitor.call(null, object) === false) { + return false; + } + for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverseBroad(child, visitor); + } + } + } + + /** + * Pulls out dependencies from an array literal with just string members. + * If string literals, will just return those string values in an array, + * skipping other items in the array. + * + * @param {Node} node an AST node. + * + * @returns {Array} an array of strings. + * If null is returned, then it means the input node was not a valid + * dependency. + */ + function getValidDeps(node) { + if (!node || node.type !== 'ArrayExpression' || !node.elements) { + return; + } + + var deps = []; + + node.elements.some(function (elem) { + if (elem.type === 'Literal') { + deps.push(elem.value); + } + }); + + return deps.length ? deps : undefined; + } + + // Detects regular or arrow function expressions as the desired expression + // type. + function isFnExpression(node) { + return (node && (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression')); + } + + /** + * Main parse function. Returns a string of any valid require or + * define/require.def calls as part of one JavaScript source string. + * @param {String} moduleName the module name that represents this file. + * It is used to create a default define if there is not one already for the + * file. This allows properly tracing dependencies for builds. Otherwise, if + * the file just has a require() call, the file dependencies will not be + * properly reflected: the file will come before its dependencies. + * @param {String} moduleName + * @param {String} fileName + * @param {String} fileContents + * @param {Object} options optional options. insertNeedsDefine: true will + * add calls to require.needsDefine() if appropriate. + * @returns {String} JS source string or null, if no require or + * define/require.def calls are found. + */ + function parse(moduleName, fileName, fileContents, options) { + options = options || {}; + + //Set up source input + var i, moduleCall, depString, + moduleDeps = [], + result = '', + moduleList = [], + needsDefine = true, + astRoot = esprima.parse(fileContents); + + parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { + if (!deps) { + deps = []; + } + + if (callName === 'define' && (!name || name === moduleName)) { + needsDefine = false; + } + + if (!name) { + //If there is no module name, the dependencies are for + //this file/default module name. + moduleDeps = moduleDeps.concat(deps); + } else { + moduleList.push({ + name: name, + deps: deps + }); + } + + if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { + return factoryIdentifier; + } + + //If define was found, no need to dive deeper, unless + //the config explicitly wants to dig deeper. + return !!options.findNestedDependencies; + }, options); + + if (options.insertNeedsDefine && needsDefine) { + result += 'require.needsDefine("' + moduleName + '");'; + } + + if (moduleDeps.length || moduleList.length) { + for (i = 0; i < moduleList.length; i++) { + moduleCall = moduleList[i]; + if (result) { + result += '\n'; + } + + //If this is the main module for this file, combine any + //"anonymous" dependencies (could come from a nested require + //call) with this module. + if (moduleCall.name === moduleName) { + moduleCall.deps = moduleCall.deps.concat(moduleDeps); + moduleDeps = []; + } + + depString = arrayToString(moduleCall.deps); + result += 'define("' + moduleCall.name + '",' + + depString + ');'; + } + if (moduleDeps.length) { + if (result) { + result += '\n'; + } + depString = arrayToString(moduleDeps); + result += 'define("' + moduleName + '",' + depString + ');'; + } + } + + return result || null; + } + + parse.traverse = traverse; + parse.traverseBroad = traverseBroad; + parse.isFnExpression = isFnExpression; + + /** + * Handles parsing a file recursively for require calls. + * @param {Array} parentNode the AST node to start with. + * @param {Function} onMatch function to call on a parse match. + * @param {Object} [options] This is normally the build config options if + * it is passed. + * @param {Object} [fnExpScope] holds list of function expresssion + * argument identifiers, set up internally, not passed in + */ + parse.recurse = function (object, onMatch, options, fnExpScope) { + //Like traverse, but skips if branches that would not be processed + //after has application that results in tests of true or false boolean + //literal values. + var keys, child, result, i, params, param, tempObject, + hasHas = options && options.has; + + fnExpScope = fnExpScope || emptyScope; + + if (!object) { + return; + } + + //If has replacement has resulted in if(true){} or if(false){}, take + //the appropriate branch and skip the other one. + if (hasHas && object.type === 'IfStatement' && object.test.type && + object.test.type === 'Literal') { + if (object.test.value) { + //Take the if branch + this.recurse(object.consequent, onMatch, options, fnExpScope); + } else { + //Take the else branch + this.recurse(object.alternate, onMatch, options, fnExpScope); + } + } else { + result = this.parseNode(object, onMatch, fnExpScope); + if (result === false) { + return; + } else if (typeof result === 'string') { + return result; + } + + //Build up a "scope" object that informs nested recurse calls if + //the define call references an identifier that is likely a UMD + //wrapped function expression argument. + //Catch (function(a) {... wrappers + if (object.type === 'ExpressionStatement' && object.expression && + object.expression.type === 'CallExpression' && object.expression.callee && + isFnExpression(object.expression.callee)) { + tempObject = object.expression.callee; + } + // Catch !function(a) {... wrappers + if (object.type === 'UnaryExpression' && object.argument && + object.argument.type === 'CallExpression' && object.argument.callee && + isFnExpression(object.argument.callee)) { + tempObject = object.argument.callee; + } + if (tempObject && tempObject.params && tempObject.params.length) { + params = tempObject.params; + fnExpScope = mixin({}, fnExpScope, true); + for (i = 0; i < params.length; i++) { + param = params[i]; + if (param.type === 'Identifier') { + fnExpScope[param.name] = true; + } + } + } + + for (i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[keys[i]]; + if (typeof child === 'object' && child !== null) { + result = this.recurse(child, onMatch, options, fnExpScope); + if (typeof result === 'string' && hasProp(fnExpScope, result)) { + //The result was still in fnExpScope so break. Otherwise, + //was a return from a a tree that had a UMD definition, + //but now out of that scope so keep siblings. + break; + } + } + } + + //Check for an identifier for a factory function identifier being + //passed in as a function expression, indicating a UMD-type of + //wrapping. + if (typeof result === 'string') { + if (hasProp(fnExpScope, result)) { + //result still in scope, keep jumping out indicating the + //identifier still in use. + return result; + } + + return; + } + } + }; + + /** + * Determines if the file defines the require/define module API. + * Specifically, it looks for the `define.amd = ` expression. + * @param {String} fileName + * @param {String} fileContents + * @returns {Boolean} + */ + parse.definesRequire = function (fileName, fileContents) { + var foundDefine = false, + foundDefineAmd = false; + + traverse(esprima.parse(fileContents), function (node) { + // Look for a top level declaration of a define, like + // var requirejs, require, define, off Program body. + if (node.type === 'Program' && node.body && node.body.length) { + foundDefine = node.body.some(function(bodyNode) { + // var define + if (bodyNode.type === 'VariableDeclaration') { + var decls = bodyNode.declarations; + if (decls) { + var hasVarDefine = decls.some(function(declNode) { + return (declNode.type === 'VariableDeclarator' && + declNode.id && + declNode.id.type === 'Identifier' && + declNode.id.name === 'define'); + }); + if (hasVarDefine) { + return true; + } + } + } + + // function define() {} + if (bodyNode.type === 'FunctionDeclaration' && + bodyNode.id && + bodyNode.id.type === 'Identifier' && + bodyNode.id.name === 'define') { + return true; + } + + + + + + + }); + } + + // Need define variable found first, before detecting define.amd. + if (foundDefine && parse.hasDefineAmd(node)) { + foundDefineAmd = true; + + //Stop traversal + return false; + } + }); + + return foundDefine && foundDefineAmd; + }; + + /** + * Finds require("") calls inside a CommonJS anonymous module wrapped in a + * define(function(require, exports, module){}) wrapper. These dependencies + * will be added to a modified define() call that lists the dependencies + * on the outside of the function. + * @param {String} fileName + * @param {String|Object} fileContents: a string of contents, or an already + * parsed AST tree. + * @returns {Array} an array of module names that are dependencies. Always + * returns an array, but could be of length zero. + */ + parse.getAnonDeps = function (fileName, fileContents) { + var astRoot = typeof fileContents === 'string' ? + esprima.parse(fileContents) : fileContents, + defFunc = this.findAnonDefineFactory(astRoot); + + return parse.getAnonDepsFromNode(defFunc); + }; + + /** + * Finds require("") calls inside a CommonJS anonymous module wrapped + * in a define function, given an AST node for the definition function. + * @param {Node} node the AST node for the definition function. + * @returns {Array} and array of dependency names. Can be of zero length. + */ + parse.getAnonDepsFromNode = function (node) { + var deps = [], + funcArgLength; + + if (node) { + this.findRequireDepNames(node, deps); + + //If no deps, still add the standard CommonJS require, exports, + //module, in that order, to the deps, but only if specified as + //function args. In particular, if exports is used, it is favored + //over the return value of the function, so only add it if asked. + funcArgLength = node.params && node.params.length; + if (funcArgLength) { + deps = (funcArgLength > 1 ? ["require", "exports", "module"] : + ["require"]).concat(deps); + } + } + return deps; + }; + + parse.isDefineNodeWithArgs = function (node) { + return node && node.type === 'CallExpression' && + node.callee && node.callee.type === 'Identifier' && + node.callee.name === 'define' && node[argPropName]; + }; + + /** + * Finds the function in define(function (require, exports, module){}); + * @param {Array} node + * @returns {Boolean} + */ + parse.findAnonDefineFactory = function (node) { + var match; + + traverse(node, function (node) { + var arg0, arg1; + + if (parse.isDefineNodeWithArgs(node)) { + + //Just the factory function passed to define + arg0 = node[argPropName][0]; + if (isFnExpression(arg0)) { + match = arg0; + return false; + } + + //A string literal module ID followed by the factory function. + arg1 = node[argPropName][1]; + if (arg0.type === 'Literal' && isFnExpression(arg1)) { + match = arg1; + return false; + } + } + }); + + return match; + }; + + /** + * Finds any config that is passed to requirejs. That includes calls to + * require/requirejs.config(), as well as require({}, ...) and + * requirejs({}, ...) + * @param {String} fileContents + * + * @returns {Object} a config details object with the following properties: + * - config: {Object} the config object found. Can be undefined if no + * config found. + * - range: {Array} the start index and end index in the contents where + * the config was found. Can be undefined if no config found. + * Can throw an error if the config in the file cannot be evaluated in + * a build context to valid JavaScript. + */ + parse.findConfig = function (fileContents) { + /*jslint evil: true */ + var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch, + quoteRegExp = /(:\s|\[\s*)(['"])/, + astRoot = esprima.parse(fileContents, { + loc: true + }); + + traverse(astRoot, function (node) { + var arg, + requireType = parse.hasRequire(node); + + if (requireType && (requireType === 'require' || + requireType === 'requirejs' || + requireType === 'requireConfig' || + requireType === 'requirejsConfig')) { + + arg = node[argPropName] && node[argPropName][0]; + + if (arg && arg.type === 'ObjectExpression') { + stringData = parse.nodeToString(fileContents, arg); + jsConfig = stringData.value; + foundRange = stringData.range; + return false; + } + } else { + arg = parse.getRequireObjectLiteral(node); + if (arg) { + stringData = parse.nodeToString(fileContents, arg); + jsConfig = stringData.value; + foundRange = stringData.range; + return false; + } + } + }); + + if (jsConfig) { + // Eval the config + quoteMatch = quoteRegExp.exec(jsConfig); + quote = (quoteMatch && quoteMatch[2]) || '"'; + foundConfig = eval('(' + jsConfig + ')'); + } + + return { + config: foundConfig, + range: foundRange, + quote: quote + }; + }; + + /** Returns the node for the object literal assigned to require/requirejs, + * for holding a declarative config. + */ + parse.getRequireObjectLiteral = function (node) { + if (node.id && node.id.type === 'Identifier' && + (node.id.name === 'require' || node.id.name === 'requirejs') && + node.init && node.init.type === 'ObjectExpression') { + return node.init; + } + }; + + /** + * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define + * Does *not* do .config calls though. See pragma.namespace for the complete + * set of namespace transforms. This function is used because require calls + * inside a define() call should not be renamed, so a simple regexp is not + * good enough. + * @param {String} fileContents the contents to transform. + * @param {String} ns the namespace, *not* including trailing dot. + * @return {String} the fileContents with the namespace applied + */ + parse.renameNamespace = function (fileContents, ns) { + var lines, + locs = [], + astRoot = esprima.parse(fileContents, { + loc: true + }); + + parse.recurse(astRoot, function (callName, config, name, deps, node) { + locs.push(node.loc); + //Do not recurse into define functions, they should be using + //local defines. + return callName !== 'define'; + }, {}); + + if (locs.length) { + lines = fileContents.split('\n'); + + //Go backwards through the found locs, adding in the namespace name + //in front. + locs.reverse(); + locs.forEach(function (loc) { + var startIndex = loc.start.column, + //start.line is 1-based, not 0 based. + lineIndex = loc.start.line - 1, + line = lines[lineIndex]; + + lines[lineIndex] = line.substring(0, startIndex) + + ns + '.' + + line.substring(startIndex, + line.length); + }); + + fileContents = lines.join('\n'); + } + + return fileContents; + }; + + /** + * Finds all dependencies specified in dependency arrays and inside + * simplified commonjs wrappers. + * @param {String} fileName + * @param {String} fileContents + * + * @returns {Array} an array of dependency strings. The dependencies + * have not been normalized, they may be relative IDs. + */ + parse.findDependencies = function (fileName, fileContents, options) { + var dependencies = [], + astRoot = esprima.parse(fileContents); + + parse.recurse(astRoot, function (callName, config, name, deps) { + if (deps) { + dependencies = dependencies.concat(deps); + } + }, options); + + return dependencies; + }; + + /** + * Finds only CJS dependencies, ones that are the form + * require('stringLiteral') + */ + parse.findCjsDependencies = function (fileName, fileContents) { + var dependencies = []; + + traverse(esprima.parse(fileContents), function (node) { + var arg; + + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && node[argPropName] && + node[argPropName].length === 1) { + arg = node[argPropName][0]; + if (arg.type === 'Literal') { + dependencies.push(arg.value); + } + } + }); + + return dependencies; + }; + + //function define() {} + parse.hasDefDefine = function (node) { + return node.type === 'FunctionDeclaration' && node.id && + node.id.type === 'Identifier' && node.id.name === 'define'; + }; + + //define.amd = ... + parse.hasDefineAmd = function (node) { + return node && node.type === 'AssignmentExpression' && + node.left && node.left.type === 'MemberExpression' && + node.left.object && node.left.object.name === 'define' && + node.left.property && node.left.property.name === 'amd'; + }; + + //define.amd reference, as in: if (define.amd) + parse.refsDefineAmd = function (node) { + return node && node.type === 'MemberExpression' && + node.object && node.object.name === 'define' && + node.object.type === 'Identifier' && + node.property && node.property.name === 'amd' && + node.property.type === 'Identifier'; + }; + + //require(), requirejs(), require.config() and requirejs.config() + parse.hasRequire = function (node) { + var callName, + c = node && node.callee; + + if (node && node.type === 'CallExpression' && c) { + if (c.type === 'Identifier' && + (c.name === 'require' || + c.name === 'requirejs')) { + //A require/requirejs({}, ...) call + callName = c.name; + } else if (c.type === 'MemberExpression' && + c.object && + c.object.type === 'Identifier' && + (c.object.name === 'require' || + c.object.name === 'requirejs') && + c.property && c.property.name === 'config') { + // require/requirejs.config({}) call + callName = c.object.name + 'Config'; + } + } + + return callName; + }; + + //define() + parse.hasDefine = function (node) { + return node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'define'; + }; + + /** + * If there is a named define in the file, returns the name. Does not + * scan for mulitple names, just the first one. + */ + parse.getNamedDefine = function (fileContents) { + var name; + traverse(esprima.parse(fileContents), function (node) { + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'define' && + node[argPropName] && node[argPropName][0] && + node[argPropName][0].type === 'Literal') { + name = node[argPropName][0].value; + return false; + } + }); + + return name; + }; + + /** + * Finds all the named define module IDs in a file. + */ + parse.getAllNamedDefines = function (fileContents, excludeMap) { + var names = []; + parse.recurse(esprima.parse(fileContents), + function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { + if (callName === 'define' && name) { + if (!excludeMap.hasOwnProperty(name)) { + names.push(name); + } + } + + //If a UMD definition that points to a factory that is an Identifier, + //indicate processing should not traverse inside the UMD definition. + if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { + return factoryIdentifier; + } + + //If define was found, no need to dive deeper, unless + //the config explicitly wants to dig deeper. + return true; + }, {}); + + return names; + }; + + /** + * Determines if define(), require({}|[]) or requirejs was called in the + * file. Also finds out if define() is declared and if define.amd is called. + */ + parse.usesAmdOrRequireJs = function (fileName, fileContents) { + var uses; + + traverse(esprima.parse(fileContents), function (node) { + var type, callName, arg; + + if (parse.hasDefDefine(node)) { + //function define() {} + type = 'declaresDefine'; + } else if (parse.hasDefineAmd(node)) { + type = 'defineAmd'; + } else { + callName = parse.hasRequire(node); + if (callName) { + arg = node[argPropName] && node[argPropName][0]; + if (arg && (arg.type === 'ObjectExpression' || + arg.type === 'ArrayExpression')) { + type = callName; + } + } else if (parse.hasDefine(node)) { + type = 'define'; + } + } + + if (type) { + if (!uses) { + uses = {}; + } + uses[type] = true; + } + }); + + return uses; + }; + + /** + * Determines if require(''), exports.x =, module.exports =, + * __dirname, __filename are used. So, not strictly traditional CommonJS, + * also checks for Node variants. + */ + parse.usesCommonJs = function (fileName, fileContents) { + var uses = null, + assignsExports = false; + + + traverse(esprima.parse(fileContents), function (node) { + var type, + exp = node.expression || node.init; + + if (node.type === 'Identifier' && + (node.name === '__dirname' || node.name === '__filename')) { + type = node.name.substring(2); + } else if (node.type === 'VariableDeclarator' && node.id && + node.id.type === 'Identifier' && + node.id.name === 'exports') { + //Hmm, a variable assignment for exports, so does not use cjs + //exports. + type = 'varExports'; + } else if (exp && exp.type === 'AssignmentExpression' && exp.left && + exp.left.type === 'MemberExpression' && exp.left.object) { + if (exp.left.object.name === 'module' && exp.left.property && + exp.left.property.name === 'exports') { + type = 'moduleExports'; + } else if (exp.left.object.name === 'exports' && + exp.left.property) { + type = 'exports'; + } else if (exp.left.object.type === 'MemberExpression' && + exp.left.object.object.name === 'module' && + exp.left.object.property.name === 'exports' && + exp.left.object.property.type === 'Identifier') { + type = 'moduleExports'; + } + + } else if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && node[argPropName] && + node[argPropName].length === 1 && + node[argPropName][0].type === 'Literal') { + type = 'require'; + } + + if (type) { + if (type === 'varExports') { + assignsExports = true; + } else if (type !== 'exports' || !assignsExports) { + if (!uses) { + uses = {}; + } + uses[type] = true; + } + } + }); + + return uses; + }; + + + parse.findRequireDepNames = function (node, deps) { + traverse(node, function (node) { + var arg; + + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && + node[argPropName] && node[argPropName].length === 1) { + + arg = node[argPropName][0]; + if (arg.type === 'Literal') { + deps.push(arg.value); + } + } + }); + }; + + /** + * Determines if a specific node is a valid require or define/require.def + * call. + * @param {Array} node + * @param {Function} onMatch a function to call when a match is found. + * It is passed the match name, and the config, name, deps possible args. + * The config, name and deps args are not normalized. + * @param {Object} fnExpScope an object whose keys are all function + * expression identifiers that should be in scope. Useful for UMD wrapper + * detection to avoid parsing more into the wrapped UMD code. + * + * @returns {String} a JS source string with the valid require/define call. + * Otherwise null. + */ + parse.parseNode = function (node, onMatch, fnExpScope) { + var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode, + args = node && node[argPropName], + callName = parse.hasRequire(node), + isUmd = false; + + if (callName === 'require' || callName === 'requirejs') { + //A plain require/requirejs call + arg = node[argPropName] && node[argPropName][0]; + if (arg && arg.type !== 'ArrayExpression') { + if (arg.type === 'ObjectExpression') { + //A config call, try the second arg. + arg = node[argPropName][1]; + } + } + + deps = getValidDeps(arg); + if (!deps) { + return; + } + + return onMatch("require", null, null, deps, node); + } else if (parse.hasDefine(node) && args && args.length) { + name = args[0]; + deps = args[1]; + factory = args[2]; + + if (name.type === 'ArrayExpression') { + //No name, adjust args + factory = deps; + deps = name; + name = null; + } else if (isFnExpression(name)) { + //Just the factory, no name or deps + factory = name; + name = deps = null; + } else if (name.type === 'Identifier' && args.length === 1 && + hasProp(fnExpScope, name.name)) { + //define(e) where e is a UMD identifier for the factory + //function. + isUmd = true; + factory = name; + name = null; + } else if (name.type !== 'Literal') { + //An object literal, just null out + name = deps = factory = null; + } + + if (name && name.type === 'Literal' && deps) { + if (isFnExpression(deps)) { + //deps is the factory + factory = deps; + deps = null; + } else if (deps.type === 'ObjectExpression') { + //deps is object literal, null out + deps = factory = null; + } else if (deps.type === 'Identifier') { + if (args.length === 2) { + //define('id', factory) + deps = factory = null; + } else if (args.length === 3 && isFnExpression(factory)) { + //define('id', depsIdentifier, factory) + //Since identifier, cannot know the deps, but do not + //error out, assume they are taken care of outside of + //static parsing. + deps = null; + } + } + } + + if (deps && deps.type === 'ArrayExpression') { + deps = getValidDeps(deps); + } else if (isFnExpression(factory)) { + //If no deps and a factory function, could be a commonjs sugar + //wrapper, scan the function for dependencies. + cjsDeps = parse.getAnonDepsFromNode(factory); + if (cjsDeps.length) { + deps = cjsDeps; + } + } else if (deps || (factory && !isUmd)) { + //Does not match the shape of an AMD call. + return; + } + + //Just save off the name as a string instead of an AST object. + if (name && name.type === 'Literal') { + name = name.value; + } + + return onMatch("define", null, name, deps, node, + (factory && factory.type === 'Identifier' ? factory.name : undefined), + fnExpScope); + } else if (node.type === 'CallExpression' && node.callee && + isFnExpression(node.callee) && + node.callee.body && node.callee.body.body && + node.callee.body.body.length === 1 && + node.callee.body.body[0].type === 'IfStatement') { + bodyNode = node.callee.body.body[0]; + //Look for a define(Identifier) case, but only if inside an + //if that has a define.amd test + if (bodyNode.consequent && bodyNode.consequent.body) { + exp = bodyNode.consequent.body[0]; + if (exp.type === 'ExpressionStatement' && exp.expression && + parse.hasDefine(exp.expression) && + exp.expression.arguments && + exp.expression.arguments.length === 1 && + exp.expression.arguments[0].type === 'Identifier') { + + //Calls define(Identifier) as first statement in body. + //Confirm the if test references define.amd + traverse(bodyNode.test, function (node) { + if (parse.refsDefineAmd(node)) { + refsDefine = true; + return false; + } + }); + + if (refsDefine) { + return onMatch("define", null, null, null, exp.expression, + exp.expression.arguments[0].name, fnExpScope); + } + } + } + } + }; + + /** + * Converts an AST node into a JS source string by extracting + * the node's location from the given contents string. Assumes + * esprima.parse() with loc was done. + * @param {String} contents + * @param {Object} node + * @returns {String} a JS source string. + */ + parse.nodeToString = function (contents, node) { + var extracted, + loc = node.loc, + lines = contents.split('\n'), + firstLine = loc.start.line > 1 ? + lines.slice(0, loc.start.line - 1).join('\n') + '\n' : + '', + preamble = firstLine + + lines[loc.start.line - 1].substring(0, loc.start.column); + + if (loc.start.line === loc.end.line) { + extracted = lines[loc.start.line - 1].substring(loc.start.column, + loc.end.column); + } else { + extracted = lines[loc.start.line - 1].substring(loc.start.column) + + '\n' + + lines.slice(loc.start.line, loc.end.line - 1).join('\n') + + '\n' + + lines[loc.end.line - 1].substring(0, loc.end.column); + } + + return { + value: extracted, + range: [ + preamble.length, + preamble.length + extracted.length + ] + }; + }; + + /** + * Extracts license comments from JS text. + * @param {String} fileName + * @param {String} contents + * @returns {String} a string of license comments. + */ + parse.getLicenseComments = function (fileName, contents) { + var commentNode, refNode, subNode, value, i, j, + //xpconnect's Reflect does not support comment or range, but + //prefer continued operation vs strict parity of operation, + //as license comments can be expressed in other ways, like + //via wrap args, or linked via sourcemaps. + ast = esprima.parse(contents, { + comment: true, + range: true + }), + result = '', + existsMap = {}, + lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n'; + + if (ast.comments) { + for (i = 0; i < ast.comments.length; i++) { + commentNode = ast.comments[i]; + + if (commentNode.type === 'Line') { + value = '//' + commentNode.value + lineEnd; + refNode = commentNode; + + if (i + 1 >= ast.comments.length) { + value += lineEnd; + } else { + //Look for immediately adjacent single line comments + //since it could from a multiple line comment made out + //of single line comments. Like this comment. + for (j = i + 1; j < ast.comments.length; j++) { + subNode = ast.comments[j]; + if (subNode.type === 'Line' && + subNode.range[0] === refNode.range[1] + 1) { + //Adjacent single line comment. Collect it. + value += '//' + subNode.value + lineEnd; + refNode = subNode; + } else { + //No more single line comment blocks. Break out + //and continue outer looping. + break; + } + } + value += lineEnd; + i = j - 1; + } + } else { + value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd; + } + + if (!existsMap[value] && (value.indexOf('license') !== -1 || + (commentNode.type === 'Block' && + value.indexOf('/*!') === 0) || + value.indexOf('opyright') !== -1 || + value.indexOf('(c)') !== -1)) { + + result += value; + existsMap[value] = true; + } + + } + } + + return result; + }; + + return parse; +}); +/*global define */ + +define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'], +function (esprima, parse, logger, lang) { + 'use strict'; + var transform, + baseIndentRegExp = /^([ \t]+)/, + indentRegExp = /\{[\r\n]+([ \t]+)/, + keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/, + bulkIndentRegExps = { + '\n': /\n/g, + '\r\n': /\r\n/g + }; + + function applyIndent(str, indent, lineReturn) { + var regExp = bulkIndentRegExps[lineReturn]; + return str.replace(regExp, '$&' + indent); + } + + transform = { + toTransport: function (namespace, moduleName, path, contents, onFound, options) { + options = options || {}; + + var astRoot, contentLines, modLine, + foundAnon, + scanCount = 0, + scanReset = false, + defineInfos = [], + applySourceUrl = function (contents) { + if (options.useSourceUrl) { + contents = 'eval("' + lang.jsEscape(contents) + + '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') + + path + + '");\n'; + } + return contents; + }; + + try { + astRoot = esprima.parse(contents, { + loc: true + }); + } catch (e) { + logger.trace('toTransport skipping ' + path + ': ' + + e.toString()); + return contents; + } + + //Find the define calls and their position in the files. + parse.traverse(astRoot, function (node) { + var args, firstArg, firstArgLoc, factoryNode, + needsId, depAction, foundId, init, + sourceUrlData, range, + namespaceExists = false; + + // If a bundle script with a define declaration, do not + // parse any further at this level. Likely a built layer + // by some other tool. + if (node.type === 'VariableDeclarator' && + node.id && node.id.name === 'define' && + node.id.type === 'Identifier') { + init = node.init; + if (init && init.callee && + init.callee.type === 'CallExpression' && + init.callee.callee && + init.callee.callee.type === 'Identifier' && + init.callee.callee.name === 'require' && + init.callee.arguments && init.callee.arguments.length === 1 && + init.callee.arguments[0].type === 'Literal' && + init.callee.arguments[0].value && + init.callee.arguments[0].value.indexOf('amdefine') !== -1) { + // the var define = require('amdefine')(module) case, + // keep going in that case. + } else { + return false; + } + } + + namespaceExists = namespace && + node.type === 'CallExpression' && + node.callee && node.callee.object && + node.callee.object.type === 'Identifier' && + node.callee.object.name === namespace && + node.callee.property.type === 'Identifier' && + node.callee.property.name === 'define'; + + if (namespaceExists || parse.isDefineNodeWithArgs(node)) { + //The arguments are where its at. + args = node.arguments; + if (!args || !args.length) { + return; + } + + firstArg = args[0]; + firstArgLoc = firstArg.loc; + + if (args.length === 1) { + if (firstArg.type === 'Identifier') { + //The define(factory) case, but + //only allow it if one Identifier arg, + //to limit impact of false positives. + needsId = true; + depAction = 'empty'; + } else if (parse.isFnExpression(firstArg)) { + //define(function(){}) + factoryNode = firstArg; + needsId = true; + depAction = 'scan'; + } else if (firstArg.type === 'ObjectExpression') { + //define({}); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'Literal' && + typeof firstArg.value === 'number') { + //define('12345'); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'UnaryExpression' && + firstArg.operator === '-' && + firstArg.argument && + firstArg.argument.type === 'Literal' && + typeof firstArg.argument.value === 'number') { + //define('-12345'); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'MemberExpression' && + firstArg.object && + firstArg.property && + firstArg.property.type === 'Identifier') { + //define(this.key); + needsId = true; + depAction = 'empty'; + } + } else if (firstArg.type === 'ArrayExpression') { + //define([], ...); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'Literal' && + typeof firstArg.value === 'string') { + //define('string', ....) + //Already has an ID. + needsId = false; + if (args.length === 2 && + parse.isFnExpression(args[1])) { + //Needs dependency scanning. + factoryNode = args[1]; + depAction = 'scan'; + } else { + depAction = 'skip'; + } + } else { + //Unknown define entity, keep looking, even + //in the subtree for this node. + return; + } + + range = { + foundId: foundId, + needsId: needsId, + depAction: depAction, + namespaceExists: namespaceExists, + node: node, + defineLoc: node.loc, + firstArgLoc: firstArgLoc, + factoryNode: factoryNode, + sourceUrlData: sourceUrlData + }; + + //Only transform ones that do not have IDs. If it has an + //ID but no dependency array, assume it is something like + //a phonegap implementation, that has its own internal + //define that cannot handle dependency array constructs, + //and if it is a named module, then it means it has been + //set for transport form. + if (range.needsId) { + if (foundAnon) { + logger.trace(path + ' has more than one anonymous ' + + 'define. May be a built file from another ' + + 'build system like, Ender. Skipping normalization.'); + defineInfos = []; + return false; + } else { + foundAnon = range; + defineInfos.push(range); + } + } else if (depAction === 'scan') { + scanCount += 1; + if (scanCount > 1) { + //Just go back to an array that just has the + //anon one, since this is an already optimized + //file like the phonegap one. + if (!scanReset) { + defineInfos = foundAnon ? [foundAnon] : []; + scanReset = true; + } + } else { + defineInfos.push(range); + } + } + } + }); + + + if (!defineInfos.length) { + return applySourceUrl(contents); + } + + //Reverse the matches, need to start from the bottom of + //the file to modify it, so that the ranges are still true + //further up. + defineInfos.reverse(); + + contentLines = contents.split('\n'); + + modLine = function (loc, contentInsertion) { + var startIndex = loc.start.column, + //start.line is 1-based, not 0 based. + lineIndex = loc.start.line - 1, + line = contentLines[lineIndex]; + contentLines[lineIndex] = line.substring(0, startIndex) + + contentInsertion + + line.substring(startIndex, + line.length); + }; + + defineInfos.forEach(function (info) { + var deps, + contentInsertion = '', + depString = ''; + + //Do the modifications "backwards", in other words, start with the + //one that is farthest down and work up, so that the ranges in the + //defineInfos still apply. So that means deps, id, then namespace. + if (info.needsId && moduleName) { + contentInsertion += "'" + moduleName + "',"; + } + + if (info.depAction === 'scan') { + deps = parse.getAnonDepsFromNode(info.factoryNode); + + if (deps.length) { + depString = '[' + deps.map(function (dep) { + return "'" + dep + "'"; + }) + ']'; + } else { + depString = '[]'; + } + depString += ','; + + if (info.factoryNode) { + //Already have a named module, need to insert the + //dependencies after the name. + modLine(info.factoryNode.loc, depString); + } else { + contentInsertion += depString; + } + } + + if (contentInsertion) { + modLine(info.firstArgLoc, contentInsertion); + } + + //Do namespace last so that ui does not mess upthe parenRange + //used above. + if (namespace && !info.namespaceExists) { + modLine(info.defineLoc, namespace + '.'); + } + + //Notify any listener for the found info + if (onFound) { + onFound(info); + } + }); + + contents = contentLines.join('\n'); + + return applySourceUrl(contents); + }, + + /** + * Modify the contents of a require.config/requirejs.config call. This + * call will LOSE any existing comments that are in the config string. + * + * @param {String} fileContents String that may contain a config call + * @param {Function} onConfig Function called when the first config + * call is found. It will be passed an Object which is the current + * config, and the onConfig function should return an Object to use + * as the config. + * @return {String} the fileContents with the config changes applied. + */ + modifyConfig: function (fileContents, onConfig) { + var details = parse.findConfig(fileContents), + config = details.config; + + if (config) { + config = onConfig(config); + if (config) { + return transform.serializeConfig(config, + fileContents, + details.range[0], + details.range[1], + { + quote: details.quote + }); + } + } + + return fileContents; + }, + + serializeConfig: function (config, fileContents, start, end, options) { + //Calculate base level of indent + var indent, match, configString, outDentRegExp, + baseIndent = '', + startString = fileContents.substring(0, start), + existingConfigString = fileContents.substring(start, end), + lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n', + lastReturnIndex = startString.lastIndexOf('\n'); + + //Get the basic amount of indent for the require config call. + if (lastReturnIndex === -1) { + lastReturnIndex = 0; + } + + match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start)); + if (match && match[1]) { + baseIndent = match[1]; + } + + //Calculate internal indentation for config + match = indentRegExp.exec(existingConfigString); + if (match && match[1]) { + indent = match[1]; + } + + if (!indent || indent.length < baseIndent) { + indent = ' '; + } else { + indent = indent.substring(baseIndent.length); + } + + outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g'); + + configString = transform.objectToString(config, { + indent: indent, + lineReturn: lineReturn, + outDentRegExp: outDentRegExp, + quote: options && options.quote + }); + + //Add in the base indenting level. + configString = applyIndent(configString, baseIndent, lineReturn); + + return startString + configString + fileContents.substring(end); + }, + + /** + * Tries converting a JS object to a string. This will likely suck, and + * is tailored to the type of config expected in a loader config call. + * So, hasOwnProperty fields, strings, numbers, arrays and functions, + * no weird recursively referenced stuff. + * @param {Object} obj the object to convert + * @param {Object} options options object with the following values: + * {String} indent the indentation to use for each level + * {String} lineReturn the type of line return to use + * {outDentRegExp} outDentRegExp the regexp to use to outdent functions + * {String} quote the quote type to use, ' or ". Optional. Default is " + * @param {String} totalIndent the total indent to print for this level + * @return {String} a string representation of the object. + */ + objectToString: function (obj, options, totalIndent) { + var startBrace, endBrace, nextIndent, + first = true, + value = '', + lineReturn = options.lineReturn, + indent = options.indent, + outDentRegExp = options.outDentRegExp, + quote = options.quote || '"'; + + totalIndent = totalIndent || ''; + nextIndent = totalIndent + indent; + + if (obj === null) { + value = 'null'; + } else if (obj === undefined) { + value = 'undefined'; + } else if (typeof obj === 'number' || typeof obj === 'boolean') { + value = obj; + } else if (typeof obj === 'string') { + //Use double quotes in case the config may also work as JSON. + value = quote + lang.jsEscape(obj) + quote; + } else if (lang.isArray(obj)) { + lang.each(obj, function (item, i) { + value += (i !== 0 ? ',' + lineReturn : '' ) + + nextIndent + + transform.objectToString(item, + options, + nextIndent); + }); + + startBrace = '['; + endBrace = ']'; + } else if (lang.isFunction(obj) || lang.isRegExp(obj)) { + //The outdent regexp just helps pretty up the conversion + //just in node. Rhino strips comments and does a different + //indent scheme for Function toString, so not really helpful + //there. + value = obj.toString().replace(outDentRegExp, '$1'); + } else { + //An object + lang.eachProp(obj, function (v, prop) { + value += (first ? '': ',' + lineReturn) + + nextIndent + + (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+ + ': ' + + transform.objectToString(v, + options, + nextIndent); + first = false; + }); + startBrace = '{'; + endBrace = '}'; + } + + if (startBrace) { + value = startBrace + + lineReturn + + value + + lineReturn + totalIndent + + endBrace; + } + + return value; + } + }; + + return transform; +}); +/*jslint regexp: true, plusplus: true */ +/*global define: false */ + +define('pragma', ['parse', 'logger'], function (parse, logger) { + 'use strict'; + function Temp() {} + + function create(obj, mixin) { + Temp.prototype = obj; + var temp = new Temp(), prop; + + //Avoid any extra memory hanging around + Temp.prototype = null; + + if (mixin) { + for (prop in mixin) { + if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) { + temp[prop] = mixin[prop]; + } + } + } + + return temp; // Object + } + + var pragma = { + conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/, + useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g, + hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g, + configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g, + nsWrapRegExp: /\/\*requirejs namespace: true \*\//, + apiDefRegExp: /var requirejs,\s*require,\s*define;/, + defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g, + defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g, + defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g, + defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g, + defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, + defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/, + defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/, + defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/, + amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g, + + removeStrict: function (contents, config) { + return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1'); + }, + + namespace: function (fileContents, ns, onLifecycleName) { + if (ns) { + //Namespace require/define calls + fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3('); + + + fileContents = parse.renameNamespace(fileContents, ns); + + //Namespace define ternary use: + fileContents = fileContents.replace(pragma.defineTernaryRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define"); + + //Namespace define jquery use: + fileContents = fileContents.replace(pragma.defineJQueryRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery"); + + //Namespace has.js define use: + fileContents = fileContents.replace(pragma.defineHasRegExp, + "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd"); + + //Namespace async.js define use: + fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp, + "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd"); + + //Namespace define checks. + //Do these ones last, since they are a subset of the more specific + //checks above. + fileContents = fileContents.replace(pragma.defineCheckRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd"); + fileContents = fileContents.replace(pragma.defineStringCheckRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']"); + fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp, + "'function' === typeof " + ns + ".define && " + ns + ".define.amd"); + fileContents = fileContents.replace(pragma.defineExistsRegExp, + "typeof " + ns + ".define !== 'undefined'"); + + //Check for require.js with the require/define definitions + if (pragma.apiDefRegExp.test(fileContents) && + fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) { + //Wrap the file contents in a typeof check, and a function + //to contain the API globals. + fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" + + "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' + + fileContents + + "\n" + + ns + ".requirejs = requirejs;" + + ns + ".require = require;" + + ns + ".define = define;\n" + + "}\n}());"; + } + + //Finally, if the file wants a special wrapper because it ties + //in to the requirejs internals in a way that would not fit + //the above matches, do that. Look for /*requirejs namespace: true*/ + if (pragma.nsWrapRegExp.test(fileContents)) { + //Remove the pragma. + fileContents = fileContents.replace(pragma.nsWrapRegExp, ''); + + //Alter the contents. + fileContents = '(function () {\n' + + 'var require = ' + ns + '.require,' + + 'requirejs = ' + ns + '.requirejs,' + + 'define = ' + ns + '.define;\n' + + fileContents + + '\n}());'; + } + } + + return fileContents; + }, + + /** + * processes the fileContents for some //>> conditional statements + */ + process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) { + /*jslint evil: true */ + var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine, + matches, type, marker, condition, isTrue, endRegExp, endMatches, + endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps, + i, dep, moduleName, collectorMod, + lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has, + //Legacy arg defined to help in dojo conversion script. Remove later + //when dojo no longer needs conversion: + kwArgs = pragmas; + + //Mix in a specific lifecycle scoped object, to allow targeting + //some pragmas/has tests to only when files are saved, or at different + //lifecycle events. Do not bother with kwArgs in this section, since + //the old dojo kwArgs were for all points in the build lifecycle. + if (onLifecycleName) { + lifecyclePragmas = config['pragmas' + onLifecycleName]; + lifecycleHas = config['has' + onLifecycleName]; + + if (lifecyclePragmas) { + pragmas = create(pragmas || {}, lifecyclePragmas); + } + + if (lifecycleHas) { + hasConfig = create(hasConfig || {}, lifecycleHas); + } + } + + //Replace has references if desired + if (hasConfig) { + fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) { + if (hasConfig.hasOwnProperty(test)) { + return !!hasConfig[test]; + } + return match; + }); + } + + if (!config.skipPragmas) { + + while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) { + //Found a conditional. Get the conditional line. + lineEndIndex = fileContents.indexOf("\n", foundIndex); + if (lineEndIndex === -1) { + lineEndIndex = fileContents.length - 1; + } + + //Increment startIndex past the line so the next conditional search can be done. + startIndex = lineEndIndex + 1; + + //Break apart the conditional. + conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1); + matches = conditionLine.match(pragma.conditionalRegExp); + if (matches) { + type = matches[1]; + marker = matches[2]; + condition = matches[3]; + isTrue = false; + //See if the condition is true. + try { + isTrue = !!eval("(" + condition + ")"); + } catch (e) { + throw "Error in file: " + + fileName + + ". Conditional comment: " + + conditionLine + + " failed with this error: " + e; + } + + //Find the endpoint marker. + endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g"); + endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length)); + if (endMatches) { + endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length; + + //Find the next line return based on the match position. + lineEndIndex = fileContents.indexOf("\n", endMarkerIndex); + if (lineEndIndex === -1) { + lineEndIndex = fileContents.length - 1; + } + + //Should we include the segment? + shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue)); + + //Remove the conditional comments, and optionally remove the content inside + //the conditional comments. + startLength = startIndex - foundIndex; + fileContents = fileContents.substring(0, foundIndex) + + (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") + + fileContents.substring(lineEndIndex + 1, fileContents.length); + + //Move startIndex to foundIndex, since that is the new position in the file + //where we need to look for more conditionals in the next while loop pass. + startIndex = foundIndex; + } else { + throw "Error in file: " + + fileName + + ". Cannot find end marker for conditional comment: " + + conditionLine; + + } + } + } + } + + //If need to find all plugin resources to optimize, do that now, + //before namespacing, since the namespacing will change the API + //names. + //If there is a plugin collector, scan the file for plugin resources. + if (config.optimizeAllPluginResources && pluginCollector) { + try { + deps = parse.findDependencies(fileName, fileContents); + if (deps.length) { + for (i = 0; i < deps.length; i++) { + dep = deps[i]; + if (dep.indexOf('!') !== -1) { + moduleName = dep.split('!')[0]; + collectorMod = pluginCollector[moduleName]; + if (!collectorMod) { + collectorMod = pluginCollector[moduleName] = []; + } + collectorMod.push(dep); + } + } + } + } catch (eDep) { + logger.error('Parse error looking for plugin resources in ' + + fileName + ', skipping.'); + } + } + + //Strip amdefine use for node-shared modules. + if (!config.keepAmdefine) { + fileContents = fileContents.replace(pragma.amdefineRegExp, ''); + } + + //Do namespacing + if (onLifecycleName === 'OnSave' && config.namespace) { + fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName); + } + + + return pragma.removeStrict(fileContents, config); + } + }; + + return pragma; +}); + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false */ + +define('browser/optimize', {}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false */ + +define('node/optimize', {}); + +} + +if(env === 'rhino') { +/*jslint sloppy: true, plusplus: true */ +/*global define, java, Packages, com */ + +define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) { + + //Add .reduce to Rhino so UglifyJS can run in Rhino, + //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce + //but rewritten for brevity, and to be good enough for use by UglifyJS. + if (!Array.prototype.reduce) { + Array.prototype.reduce = function (fn /*, initialValue */) { + var i = 0, + length = this.length, + accumulator; + + if (arguments.length >= 2) { + accumulator = arguments[1]; + } else { + if (length) { + while (!(i in this)) { + i++; + } + accumulator = this[i++]; + } + } + + for (; i < length; i++) { + if (i in this) { + accumulator = fn.call(undefined, accumulator, this[i], i, this); + } + } + + return accumulator; + }; + } + + var JSSourceFilefromCode, optimize, + mapRegExp = /"file":"[^"]+"/; + + //Bind to Closure compiler, but if it is not available, do not sweat it. + try { + // Try older closure compiler that worked on Java 6 + JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); + } catch (e) { + try { + // Try for newer closure compiler that needs Java 7+ + JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); + } catch (e) { + try { + // Try Nashorn style + var stringClass = Java.type("java.lang.String").class; + JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]); + } catch (e) {} + } + } + + //Helper for closure compiler, because of weird Java-JavaScript interactions. + function closurefromCode(filename, content) { + return JSSourceFilefromCode.invoke(null, [filename, content]); + } + + + function getFileWriter(fileName, encoding) { + var outFile = new java.io.File(fileName), outWriter, parentDir; + + parentDir = outFile.getAbsoluteFile().getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getAbsolutePath(); + } + } + + if (encoding) { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); + } else { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); + } + + return new java.io.BufferedWriter(outWriter); + } + + optimize = { + closure: function (fileName, fileContents, outFileName, keepLines, config) { + config = config || {}; + var result, mappings, optimized, compressed, baseName, writer, + outBaseName, outFileNameMap, outFileNameMapContent, + srcOutFileName, concatNameMap, + jscomp = Packages.com.google.javascript.jscomp, + flags = Packages.com.google.common.flags, + //Set up source input + jsSourceFile = closurefromCode(String(fileName), String(fileContents)), + sourceListArray = new java.util.ArrayList(), + externList = new java.util.ArrayList(), + options, option, FLAG_compilation_level, compiler, externExportsPath, + Compiler = Packages.com.google.javascript.jscomp.Compiler, + CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner; + + logger.trace("Minifying file: " + fileName); + + baseName = (new java.io.File(fileName)).getName(); + + //Set up options + options = new jscomp.CompilerOptions(); + for (option in config.CompilerOptions) { + // options are false by default and jslint wanted an if statement in this for loop + if (config.CompilerOptions[option]) { + options[option] = config.CompilerOptions[option]; + } + + } + options.prettyPrint = keepLines || options.prettyPrint; + + FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS']; + FLAG_compilation_level.setOptionsForCompilationLevel(options); + + if (config.generateSourceMaps) { + mappings = new java.util.ArrayList(); + + mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js")); + options.setSourceMapLocationMappings(mappings); + options.setSourceMapOutputPath(fileName + ".map"); + } + + //If we need to pass an externs file to Closure so that it does not create aliases + //for certain symbols, do so here. + externList.addAll(CommandLineRunner.getDefaultExterns()); + if (config.externExportsPath) { + externExportsPath = config.externExportsPath; + externList.add(jscomp.SourceFile.fromFile(externExportsPath)); + } + + //Trigger the compiler + Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']); + compiler = new Compiler(); + + //fill the sourceArrrayList; we need the ArrayList because the only overload of compile + //accepting the getDefaultExterns return value (a List) also wants the sources as a List + sourceListArray.add(jsSourceFile); + + result = compiler.compile(externList, sourceListArray, options); + if (result.success) { + optimized = String(compiler.toSource()); + + if (config.generateSourceMaps && result.sourceMap && outFileName) { + outBaseName = (new java.io.File(outFileName)).getName(); + + srcOutFileName = outFileName + ".src.js"; + outFileNameMap = outFileName + ".map"; + + //If previous .map file exists, move it to the ".src.js" + //location. Need to update the sourceMappingURL part in the + //src.js file too. + if (file.exists(outFileNameMap)) { + concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map'); + file.saveFile(concatNameMap, file.readFile(outFileNameMap)); + file.saveFile(srcOutFileName, + fileContents.replace(/\/\# sourceMappingURL=(.+).map/, + '/# sourceMappingURL=$1.src.js.map')); + } else { + file.saveUtf8File(srcOutFileName, fileContents); + } + + writer = getFileWriter(outFileNameMap, "utf-8"); + result.sourceMap.appendTo(writer, outFileName); + writer.close(); + + //Not sure how better to do this, but right now the .map file + //leaks the full OS path in the "file" property. Manually + //modify it to not do that. + file.saveFile(outFileNameMap, + file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"')); + + fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map"; + } else { + fileContents = optimized; + } + return fileContents; + } else { + throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.'); + } + + return fileContents; + } + }; + + return optimize; +}); +} + +if(env === 'xpconnect') { +define('xpconnect/optimize', {}); +} +/*jslint plusplus: true, nomen: true, regexp: true */ +/*global define: false */ + +define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse', + 'pragma', 'uglifyjs', + 'source-map'], +function (lang, logger, envOptimize, file, parse, + pragma, uglify, + sourceMap) { + 'use strict'; + + var optimize, + cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig, + cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g, + cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g, + protocolRegExp = /^\w+:/, + SourceMapGenerator = sourceMap.SourceMapGenerator, + SourceMapConsumer = sourceMap.SourceMapConsumer, + es5PlusGuidance = 'If the source uses ES2015 or later syntax, please pass "optimize: \'none\'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.'; + + /** + * If an URL from a CSS url value contains start/end quotes, remove them. + * This is not done in the regexp, since my regexp fu is not that strong, + * and the CSS spec allows for ' and " in the URL if they are backslash escaped. + * @param {String} url + */ + function cleanCssUrlQuotes(url) { + //Make sure we are not ending in whitespace. + //Not very confident of the css regexps above that there will not be ending + //whitespace. + url = url.replace(/\s+$/, ""); + + if (url.charAt(0) === "'" || url.charAt(0) === "\"") { + url = url.substring(1, url.length - 1); + } + + return url; + } + + function fixCssUrlPaths(fileName, path, contents, cssPrefix) { + return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) { + var firstChar, hasProtocol, parts, i, + fixedUrlMatch = cleanCssUrlQuotes(urlMatch); + + fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/"); + + //Only do the work for relative URLs. Skip things that start with / or #, or have + //a protocol. + firstChar = fixedUrlMatch.charAt(0); + hasProtocol = protocolRegExp.test(fixedUrlMatch); + if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) { + //It is a relative URL, tack on the cssPrefix and path prefix + urlMatch = cssPrefix + path + fixedUrlMatch; + } else if (!hasProtocol) { + logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch); + } + + //Collapse .. and . + parts = urlMatch.split("/"); + for (i = parts.length - 1; i > 0; i--) { + if (parts[i] === ".") { + parts.splice(i, 1); + } else if (parts[i] === "..") { + if (i !== 0 && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 1; + } + } + } + + return "url(" + parts.join("/") + ")"; + }); + } + + /** + * Inlines nested stylesheets that have @import calls in them. + * @param {String} fileName the file name + * @param {String} fileContents the file contents + * @param {String} cssImportIgnore comma delimited string of files to ignore + * @param {String} cssPrefix string to be prefixed before relative URLs + * @param {Object} included an object used to track the files already imported + */ + function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) { + //Find the last slash in the name. + fileName = fileName.replace(lang.backSlashRegExp, "/"); + var endIndex = fileName.lastIndexOf("/"), + //Make a file path based on the last slash. + //If no slash, so must be just a file name. Use empty string then. + filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "", + //store a list of merged files + importList = [], + skippedList = []; + + //First make a pass by removing any commented out @import calls. + fileContents = fileContents.replace(cssCommentImportRegExp, ''); + + //Make sure we have a delimited ignore list to make matching faster + if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") { + cssImportIgnore += ","; + } + + fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) { + //Only process media type "all" or empty media type rules. + if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) { + skippedList.push(fileName); + return fullMatch; + } + + importFileName = cleanCssUrlQuotes(importFileName); + + //Ignore the file import if it is part of an ignore list. + if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) { + return fullMatch; + } + + //Make sure we have a unix path for the rest of the operation. + importFileName = importFileName.replace(lang.backSlashRegExp, "/"); + + try { + //if a relative path, then tack on the filePath. + //If it is not a relative path, then the readFile below will fail, + //and we will just skip that import. + var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName, + importContents = file.readFile(fullImportFileName), + importEndIndex, importPath, flat; + + //Skip the file if it has already been included. + if (included[fullImportFileName]) { + return ''; + } + included[fullImportFileName] = true; + + //Make sure to flatten any nested imports. + flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included); + importContents = flat.fileContents; + + if (flat.importList.length) { + importList.push.apply(importList, flat.importList); + } + if (flat.skippedList.length) { + skippedList.push.apply(skippedList, flat.skippedList); + } + + //Make the full import path + importEndIndex = importFileName.lastIndexOf("/"); + + //Make a file path based on the last slash. + //If no slash, so must be just a file name. Use empty string then. + importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : ""; + + //fix url() on relative import (#5) + importPath = importPath.replace(/^\.\//, ''); + + //Modify URL paths to match the path represented by this file. + importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix); + + importList.push(fullImportFileName); + return importContents; + } catch (e) { + logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName); + return fullMatch; + } + }); + + if (cssPrefix && topLevel) { + //Modify URL paths to match the path represented by this file. + fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix); + } + + return { + importList : importList, + skippedList: skippedList, + fileContents : fileContents + }; + } + + optimize = { + /** + * Optimizes a file that contains JavaScript content. Optionally collects + * plugin resources mentioned in a file, and then passes the content + * through an minifier if one is specified via config.optimize. + * + * @param {String} fileName the name of the file to optimize + * @param {String} fileContents the contents to optimize. If this is + * a null value, then fileName will be used to read the fileContents. + * @param {String} outFileName the name of the file to use for the + * saved optimized content. + * @param {Object} config the build config object. + * @param {Array} [pluginCollector] storage for any plugin resources + * found. + */ + jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) { + if (!fileContents) { + fileContents = file.readFile(fileName); + } + + fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector); + + file.saveUtf8File(outFileName, fileContents); + }, + + /** + * Optimizes a file that contains JavaScript content. Optionally collects + * plugin resources mentioned in a file, and then passes the content + * through an minifier if one is specified via config.optimize. + * + * @param {String} fileName the name of the file that matches the + * fileContents. + * @param {String} fileContents the string of JS to optimize. + * @param {Object} [config] the build config object. + * @param {Array} [pluginCollector] storage for any plugin resources + * found. + */ + js: function (fileName, fileContents, outFileName, config, pluginCollector) { + var optFunc, optConfig, + parts = (String(config.optimize)).split('.'), + optimizerName = parts[0], + keepLines = parts[1] === 'keepLines', + licenseContents = ''; + + config = config || {}; + + //Apply pragmas/namespace renaming + fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector); + + //Optimize the JS files if asked. + if (optimizerName && optimizerName !== 'none') { + optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName]; + if (!optFunc) { + throw new Error('optimizer with name of "' + + optimizerName + + '" not found for this environment'); + } + + optConfig = config[optimizerName] || {}; + if (config.generateSourceMaps) { + optConfig.generateSourceMaps = !!config.generateSourceMaps; + optConfig._buildSourceMap = config._buildSourceMap; + } + + try { + if (config.preserveLicenseComments) { + //Pull out any license comments for prepending after optimization. + try { + licenseContents = parse.getLicenseComments(fileName, fileContents); + } catch (e) { + throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString()); + } + } + + if (config.generateSourceMaps && licenseContents) { + optConfig.preamble = licenseContents; + licenseContents = ''; + } + + fileContents = licenseContents + optFunc(fileName, + fileContents, + outFileName, + keepLines, + optConfig); + if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) { + config._buildSourceMap = optConfig._buildSourceMap; + } + } catch (e) { + if (config.throwWhen && config.throwWhen.optimize) { + throw e; + } else { + logger.error(e); + } + } + } else { + if (config._buildSourceMap) { + config._buildSourceMap = null; + } + } + + return fileContents; + }, + + /** + * Optimizes one CSS file, inlining @import calls, stripping comments, and + * optionally removes line returns. + * @param {String} fileName the path to the CSS file to optimize + * @param {String} outFileName the path to save the optimized file. + * @param {Object} config the config object with the optimizeCss and + * cssImportIgnore options. + */ + cssFile: function (fileName, outFileName, config) { + + //Read in the file. Make sure we have a JS string. + var originalFileContents = file.readFile(fileName), + flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true), + //Do not use the flattened CSS if there was one that was skipped. + fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents, + startIndex, endIndex, buildText, comment; + + if (flat.skippedList.length) { + logger.warn('Cannot inline @imports for ' + fileName + + ',\nthe following files had media queries in them:\n' + + flat.skippedList.join('\n')); + } + + //Do comment removal. + try { + if (config.optimizeCss.indexOf(".keepComments") === -1) { + startIndex = 0; + //Get rid of comments. + while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) { + endIndex = fileContents.indexOf("*/", startIndex + 2); + if (endIndex === -1) { + throw "Improper comment in CSS file: " + fileName; + } + comment = fileContents.substring(startIndex, endIndex); + + if (config.preserveLicenseComments && + (comment.indexOf('license') !== -1 || + comment.indexOf('opyright') !== -1 || + comment.indexOf('(c)') !== -1)) { + //Keep the comment, just increment the startIndex + startIndex = endIndex; + } else { + fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length); + startIndex = 0; + } + } + } + //Get rid of newlines. + if (config.optimizeCss.indexOf(".keepLines") === -1) { + fileContents = fileContents.replace(/[\r\n]/g, " "); + fileContents = fileContents.replace(/\s+/g, " "); + fileContents = fileContents.replace(/\{\s/g, "{"); + fileContents = fileContents.replace(/\s\}/g, "}"); + } else { + //Remove multiple empty lines. + fileContents = fileContents.replace(/(\r\n)+/g, "\r\n"); + fileContents = fileContents.replace(/(\n)+/g, "\n"); + } + //Remove unnecessary whitespace + if (config.optimizeCss.indexOf(".keepWhitespace") === -1) { + //Remove leading and trailing whitespace from lines + fileContents = fileContents.replace(/^[ \t]+/gm, ""); + fileContents = fileContents.replace(/[ \t]+$/gm, ""); + //Remove whitespace after semicolon, colon, curly brackets and commas + fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1"); + //Remove whitespace before opening curly brackets + fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1"); + //Truncate double whitespace + fileContents = fileContents.replace(/([ \t])+/g, "$1"); + //Remove empty lines + fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,''); + } + } catch (e) { + fileContents = originalFileContents; + logger.error("Could not optimized CSS file: " + fileName + ", error: " + e); + } + + file.saveUtf8File(outFileName, fileContents); + + //text output to stdout and/or written to build.txt file + buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n"; + flat.importList.push(fileName); + buildText += flat.importList.map(function(path){ + return path.replace(config.dir, ""); + }).join("\n"); + + return { + importList: flat.importList, + buildText: buildText +"\n" + }; + }, + + /** + * Optimizes CSS files, inlining @import calls, stripping comments, and + * optionally removes line returns. + * @param {String} startDir the path to the top level directory + * @param {Object} config the config object with the optimizeCss and + * cssImportIgnore options. + */ + css: function (startDir, config) { + var buildText = "", + importList = [], + shouldRemove = config.dir && config.removeCombined, + i, fileName, result, fileList; + if (config.optimizeCss.indexOf("standard") !== -1) { + fileList = file.getFilteredFileList(startDir, /\.css$/, true); + if (fileList) { + for (i = 0; i < fileList.length; i++) { + fileName = fileList[i]; + logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName); + result = optimize.cssFile(fileName, fileName, config); + buildText += result.buildText; + if (shouldRemove) { + result.importList.pop(); + importList = importList.concat(result.importList); + } + } + } + + if (shouldRemove) { + importList.forEach(function (path) { + if (file.exists(path)) { + file.deleteFile(path); + } + }); + } + } + return buildText; + }, + + optimizers: { + uglify: function (fileName, fileContents, outFileName, keepLines, config) { + var result, existingMap, resultMap, finalMap, sourceIndex, + uconfig = {}, + existingMapPath = outFileName + '.map', + baseName = fileName && fileName.split('/').pop(); + + config = config || {}; + + lang.mixin(uconfig, config, true); + + uconfig.fromString = true; + + if (config.preamble) { + uconfig.output = {preamble: config.preamble}; + } + + + if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) { + uconfig.outSourceMap = baseName + '.map'; + + if (config._buildSourceMap) { + existingMap = JSON.parse(config._buildSourceMap); + uconfig.inSourceMap = existingMap; + } else if (file.exists(existingMapPath)) { + uconfig.inSourceMap = existingMapPath; + existingMap = JSON.parse(file.readFile(existingMapPath)); + } + } + + logger.trace("Uglify file: " + fileName); + + try { + //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, ''); + result = uglify.minify(fileContents, uconfig, baseName + '.src.js'); + if (uconfig.outSourceMap && result.map) { + resultMap = result.map; + if (!existingMap && !config._buildSourceMap) { + file.saveFile(outFileName + '.src.js', fileContents); + } + + fileContents = result.code; + + if (config._buildSourceMap) { + config._buildSourceMap = resultMap; + } else { + file.saveFile(outFileName + '.map', resultMap); + } + } else { + fileContents = result.code; + } + } catch (e) { + var errorString = e.toString(); + var isSyntaxError = /SyntaxError/.test(errorString); + throw new Error('Cannot uglify file: ' + fileName + + '. Skipping it. Error is:\n' + errorString + + (isSyntaxError ? '\n\n' + es5PlusGuidance : '')); + } + return fileContents; + } + } + }; + + return optimize; +}); +/* + * This file patches require.js to communicate with the build system. + */ + +//Using sloppy since this uses eval for some code like plugins, +//which may not be strict mode compliant. So if use strict is used +//below they will have strict rules applied and may cause an error. +/*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */ +/*global require, define: true */ + +//NOT asking for require as a dependency since the goal is to modify the +//global require below +define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function ( + file, + pragma, + parse, + lang, + logger, + commonJs, + prim +) { + + var allowRun = true, + hasProp = lang.hasProp, + falseProp = lang.falseProp, + getOwn = lang.getOwn, + // Used to strip out use strict from toString()'d functions for the + // shim config since they will explicitly want to not be bound by strict, + // but some envs, explicitly xpcshell, adds a use strict. + useStrictRegExp = /['"]use strict['"];/g, + //Absolute path if starts with /, \, or x: + absoluteUrlRegExp = /^[\/\\]|^\w:/; + + //Turn off throwing on resolution conflict, that was just an older prim + //idea about finding errors early, but does not comply with how promises + //should operate. + prim.hideResolutionConflict = true; + + //This method should be called when the patches to require should take hold. + return function () { + if (!allowRun) { + return; + } + allowRun = false; + + var layer, + pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/, + oldNewContext = require.s.newContext, + oldDef, + + //create local undefined values for module and exports, + //so that when files are evaled in this function they do not + //see the node values used for r.js + exports, + module; + + /** + * Reset "global" build caches that are kept around between + * build layer builds. Useful to do when there are multiple + * top level requirejs.optimize() calls. + */ + require._cacheReset = function () { + //Stored raw text caches, used by browser use. + require._cachedRawText = {}; + //Stored cached file contents for reuse in other layers. + require._cachedFileContents = {}; + //Store which cached files contain a require definition. + require._cachedDefinesRequireUrls = {}; + }; + require._cacheReset(); + + /** + * Makes sure the URL is something that can be supported by the + * optimization tool. + * @param {String} url + * @returns {Boolean} + */ + require._isSupportedBuildUrl = function (url) { + //Ignore URLs with protocols, hosts or question marks, means either network + //access is needed to fetch it or it is too dynamic. Note that + //on Windows, full paths are used for some urls, which include + //the drive, like c:/something, so need to test for something other + //than just a colon. + if (url.indexOf("://") === -1 && url.indexOf("?") === -1 && + url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) { + return true; + } else { + if (!layer.ignoredUrls[url]) { + if (url.indexOf('empty:') === -1) { + logger.info('Cannot optimize network URL, skipping: ' + url); + } + layer.ignoredUrls[url] = true; + } + return false; + } + }; + + function normalizeUrlWithBase(context, moduleName, url) { + //Adjust the URL if it was not transformed to use baseUrl, but only + //if the URL is not already an absolute path. + if (require.jsExtRegExp.test(moduleName) && + !absoluteUrlRegExp.test(url)) { + url = (context.config.dir || context.config.dirBaseUrl) + url; + } + return url; + } + + //Overrides the new context call to add existing tracking features. + require.s.newContext = function (name) { + var context = oldNewContext(name), + oldEnable = context.enable, + moduleProto = context.Module.prototype, + oldInit = moduleProto.init, + oldCallPlugin = moduleProto.callPlugin; + + //Only do this for the context used for building. + if (name === '_') { + //For build contexts, do everything sync + context.nextTick = function (fn) { + fn(); + }; + + context.needFullExec = {}; + context.fullExec = {}; + context.plugins = {}; + context.buildShimExports = {}; + + //Override the shim exports function generator to just + //spit out strings that can be used in the stringified + //build output. + context.makeShimExports = function (value) { + var fn; + if (context.config.wrapShim) { + fn = function () { + var str = 'return '; + // If specifies an export that is just a global + // name, no dot for a `this.` and such, then also + // attach to the global, for `var a = {}` files + // where the function closure would hide that from + // the global object. + if (value.exports && value.exports.indexOf('.') === -1) { + str += 'root.' + value.exports + ' = '; + } + + if (value.init) { + str += '(' + value.init.toString() + .replace(useStrictRegExp, '') + '.apply(this, arguments))'; + } + if (value.init && value.exports) { + str += ' || '; + } + if (value.exports) { + str += value.exports; + } + str += ';'; + return str; + }; + } else { + fn = function () { + return '(function (global) {\n' + + ' return function () {\n' + + ' var ret, fn;\n' + + (value.init ? + (' fn = ' + value.init.toString() + .replace(useStrictRegExp, '') + ';\n' + + ' ret = fn.apply(global, arguments);\n') : '') + + (value.exports ? + ' return ret || global.' + value.exports + ';\n' : + ' return ret;\n') + + ' };\n' + + '}(this))'; + }; + } + + return fn; + }; + + context.enable = function (depMap, parent) { + var id = depMap.id, + parentId = parent && parent.map.id, + needFullExec = context.needFullExec, + fullExec = context.fullExec, + mod = getOwn(context.registry, id); + + if (mod && !mod.defined) { + if (parentId && getOwn(needFullExec, parentId)) { + needFullExec[id] = depMap; + } + + } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) || + (parentId && getOwn(needFullExec, parentId) && + falseProp(fullExec, id))) { + context.require.undef(id); + } + + return oldEnable.apply(context, arguments); + }; + + //Override load so that the file paths can be collected. + context.load = function (moduleName, url) { + /*jslint evil: true */ + var contents, pluginBuilderMatch, builderName, + shim, shimExports; + + //Do not mark the url as fetched if it is + //not an empty: URL, used by the optimizer. + //In that case we need to be sure to call + //load() for each module that is mapped to + //empty: so that dependencies are satisfied + //correctly. + if (url.indexOf('empty:') === 0) { + delete context.urlFetched[url]; + } + + //Only handle urls that can be inlined, so that means avoiding some + //URLs like ones that require network access or may be too dynamic, + //like JSONP + if (require._isSupportedBuildUrl(url)) { + //Adjust the URL if it was not transformed to use baseUrl. + url = normalizeUrlWithBase(context, moduleName, url); + + //Save the module name to path and path to module name mappings. + layer.buildPathMap[moduleName] = url; + layer.buildFileToModule[url] = moduleName; + + if (hasProp(context.plugins, moduleName)) { + //plugins need to have their source evaled as-is. + context.needFullExec[moduleName] = true; + } + + prim().start(function () { + if (hasProp(require._cachedFileContents, url) && + (falseProp(context.needFullExec, moduleName) || + getOwn(context.fullExec, moduleName))) { + contents = require._cachedFileContents[url]; + + //If it defines require, mark it so it can be hoisted. + //Done here and in the else below, before the + //else block removes code from the contents. + //Related to #263 + if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) { + layer.existingRequireUrl = url; + } + } else { + //Load the file contents, process for conditionals, then + //evaluate it. + return require._cacheReadAsync(url).then(function (text) { + contents = text; + + if (context.config.cjsTranslate && + (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) { + contents = commonJs.convert(url, contents); + } + + //If there is a read filter, run it now. + if (context.config.onBuildRead) { + contents = context.config.onBuildRead(moduleName, url, contents); + } + + contents = pragma.process(url, contents, context.config, 'OnExecute'); + + //Find out if the file contains a require() definition. Need to know + //this so we can inject plugins right after it, but before they are needed, + //and to make sure this file is first, so that define calls work. + try { + if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) { + layer.existingRequireUrl = url; + require._cachedDefinesRequireUrls[url] = true; + } + } catch (e1) { + throw new Error('Parse error using esprima ' + + 'for file: ' + url + '\n' + e1); + } + }).then(function () { + if (hasProp(context.plugins, moduleName)) { + //This is a loader plugin, check to see if it has a build extension, + //otherwise the plugin will act as the plugin builder too. + pluginBuilderMatch = pluginBuilderRegExp.exec(contents); + if (pluginBuilderMatch) { + //Load the plugin builder for the plugin contents. + builderName = context.makeModuleMap(pluginBuilderMatch[3], + context.makeModuleMap(moduleName), + null, + true).id; + return require._cacheReadAsync(context.nameToUrl(builderName)); + } + } + return contents; + }).then(function (text) { + contents = text; + + //Parse out the require and define calls. + //Do this even for plugins in case they have their own + //dependencies that may be separate to how the pluginBuilder works. + try { + if (falseProp(context.needFullExec, moduleName)) { + contents = parse(moduleName, url, contents, { + insertNeedsDefine: true, + has: context.config.has, + findNestedDependencies: context.config.findNestedDependencies + }); + } + } catch (e2) { + throw new Error('Parse error using esprima ' + + 'for file: ' + url + '\n' + e2); + } + + require._cachedFileContents[url] = contents; + }); + } + }).then(function () { + if (contents) { + eval(contents); + } + + try { + //If have a string shim config, and this is + //a fully executed module, try to see if + //it created a variable in this eval scope + if (getOwn(context.needFullExec, moduleName)) { + shim = getOwn(context.config.shim, moduleName); + if (shim && shim.exports) { + shimExports = eval(shim.exports); + if (typeof shimExports !== 'undefined') { + context.buildShimExports[moduleName] = shimExports; + } + } + } + + //Need to close out completion of this module + //so that listeners will get notified that it is available. + context.completeLoad(moduleName); + } catch (e) { + //Track which module could not complete loading. + if (!e.moduleTree) { + e.moduleTree = []; + } + e.moduleTree.push(moduleName); + throw e; + } + }).then(null, function (eOuter) { + + if (!eOuter.fileName) { + eOuter.fileName = url; + } + throw eOuter; + }).end(); + } else { + //With unsupported URLs still need to call completeLoad to + //finish loading. + context.completeLoad(moduleName); + } + }; + + //Marks module has having a name, and optionally executes the + //callback, but only if it meets certain criteria. + context.execCb = function (name, cb, args, exports) { + var buildShimExports = getOwn(layer.context.buildShimExports, name); + + if (buildShimExports) { + return buildShimExports; + } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) { + return cb.apply(exports, args); + } + return undefined; + }; + + moduleProto.init = function (depMaps) { + if (context.needFullExec[this.map.id]) { + lang.each(depMaps, lang.bind(this, function (depMap) { + if (typeof depMap === 'string') { + depMap = context.makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, true); + } + + if (!context.fullExec[depMap.id]) { + context.require.undef(depMap.id); + } + })); + } + + return oldInit.apply(this, arguments); + }; + + moduleProto.callPlugin = function () { + var map = this.map, + pluginMap = context.makeModuleMap(map.prefix), + pluginId = pluginMap.id, + pluginMod = getOwn(context.registry, pluginId); + + context.plugins[pluginId] = true; + context.needFullExec[pluginId] = map; + + //If the module is not waiting to finish being defined, + //undef it and start over, to get full execution. + if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) { + context.require.undef(pluginMap.id); + } + + return oldCallPlugin.apply(this, arguments); + }; + } + + return context; + }; + + //Clear up the existing context so that the newContext modifications + //above will be active. + delete require.s.contexts._; + + /** Reset state for each build layer pass. */ + require._buildReset = function () { + var oldContext = require.s.contexts._; + + //Clear up the existing context. + delete require.s.contexts._; + + //Set up new context, so the layer object can hold onto it. + require({}); + + layer = require._layer = { + buildPathMap: {}, + buildFileToModule: {}, + buildFilePaths: [], + pathAdded: {}, + modulesWithNames: {}, + needsDefine: {}, + existingRequireUrl: "", + ignoredUrls: {}, + context: require.s.contexts._ + }; + + //Return the previous context in case it is needed, like for + //the basic config object. + return oldContext; + }; + + require._buildReset(); + + //Override define() to catch modules that just define an object, so that + //a dummy define call is not put in the build file for them. They do + //not end up getting defined via context.execCb, so we need to catch them + //at the define call. + oldDef = define; + + //This function signature does not have to be exact, just match what we + //are looking for. + define = function (name) { + if (typeof name === "string" && falseProp(layer.needsDefine, name)) { + layer.modulesWithNames[name] = true; + } + return oldDef.apply(require, arguments); + }; + + define.amd = oldDef.amd; + + //Add some utilities for plugins + require._readFile = file.readFile; + require._fileExists = function (path) { + return file.exists(path); + }; + + //Called when execManager runs for a dependency. Used to figure out + //what order of execution. + require.onResourceLoad = function (context, map) { + var id = map.id, + url; + + // Fix up any maps that need to be normalized as part of the fullExec + // plumbing for plugins to participate in the build. + if (context.plugins && lang.hasProp(context.plugins, id)) { + lang.eachProp(context.needFullExec, function(value, prop) { + // For plugin entries themselves, they do not have a map + // value in needFullExec, just a "true" entry. + if (value !== true && value.prefix === id && value.unnormalized) { + var map = context.makeModuleMap(value.originalName, value.parentMap); + context.needFullExec[map.id] = map; + } + }); + } + + //If build needed a full execution, indicate it + //has been done now. But only do it if the context is tracking + //that. Only valid for the context used in a build, not for + //other contexts being run, like for useLib, plain requirejs + //use in node/rhino. + if (context.needFullExec && getOwn(context.needFullExec, id)) { + context.fullExec[id] = map; + } + + //A plugin. + if (map.prefix) { + if (falseProp(layer.pathAdded, id)) { + layer.buildFilePaths.push(id); + //For plugins the real path is not knowable, use the name + //for both module to file and file to module mappings. + layer.buildPathMap[id] = id; + layer.buildFileToModule[id] = id; + layer.modulesWithNames[id] = true; + layer.pathAdded[id] = true; + } + } else if (map.url && require._isSupportedBuildUrl(map.url)) { + //If the url has not been added to the layer yet, and it + //is from an actual file that was loaded, add it now. + url = normalizeUrlWithBase(context, id, map.url); + if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) { + //Remember the list of dependencies for this layer. + layer.buildFilePaths.push(url); + layer.pathAdded[url] = true; + } + } + }; + + //Called by output of the parse() function, when a file does not + //explicitly call define, probably just require, but the parse() + //function normalizes on define() for dependency mapping and file + //ordering works correctly. + require.needsDefine = function (moduleName) { + layer.needsDefine[moduleName] = true; + }; + }; +}); +/*jslint */ +/*global define: false, console: false */ + +define('commonJs', ['env!env/file', 'parse'], function (file, parse) { + 'use strict'; + var commonJs = { + //Set to false if you do not want this file to log. Useful in environments + //like node where you want the work to happen without noise. + useLog: true, + + convertDir: function (commonJsPath, savePath) { + var fileList, i, + jsFileRegExp = /\.js$/, + fileName, convertedFileName, fileContents; + + //Get list of files to convert. + fileList = file.getFilteredFileList(commonJsPath, /\w/, true); + + //Normalize on front slashes and make sure the paths do not end in a slash. + commonJsPath = commonJsPath.replace(/\\/g, "/"); + savePath = savePath.replace(/\\/g, "/"); + if (commonJsPath.charAt(commonJsPath.length - 1) === "/") { + commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1); + } + if (savePath.charAt(savePath.length - 1) === "/") { + savePath = savePath.substring(0, savePath.length - 1); + } + + //Cycle through all the JS files and convert them. + if (!fileList || !fileList.length) { + if (commonJs.useLog) { + if (commonJsPath === "convert") { + //A request just to convert one file. + console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath))); + } else { + console.log("No files to convert in directory: " + commonJsPath); + } + } + } else { + for (i = 0; i < fileList.length; i++) { + fileName = fileList[i]; + convertedFileName = fileName.replace(commonJsPath, savePath); + + //Handle JS files. + if (jsFileRegExp.test(fileName)) { + fileContents = file.readFile(fileName); + fileContents = commonJs.convert(fileName, fileContents); + file.saveUtf8File(convertedFileName, fileContents); + } else { + //Just copy the file over. + file.copyFile(fileName, convertedFileName, true); + } + } + } + }, + + /** + * Does the actual file conversion. + * + * @param {String} fileName the name of the file. + * + * @param {String} fileContents the contents of a file :) + * + * @returns {String} the converted contents + */ + convert: function (fileName, fileContents) { + //Strip out comments. + try { + var preamble = '', + commonJsProps = parse.usesCommonJs(fileName, fileContents); + + //First see if the module is not already RequireJS-formatted. + if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) { + return fileContents; + } + + if (commonJsProps.dirname || commonJsProps.filename) { + preamble = 'var __filename = module.uri || "", ' + + '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); '; + } + + //Construct the wrapper boilerplate. + fileContents = 'define(function (require, exports, module) {' + + preamble + + fileContents + + '\n});\n'; + + } catch (e) { + console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e); + return fileContents; + } + + return fileContents; + } + }; + + return commonJs; +}); +/*jslint plusplus: true, nomen: true, regexp: true */ +/*global define, requirejs, java, process, console */ + + +define('build', function (require) { + 'use strict'; + + var build, + lang = require('lang'), + prim = require('prim'), + logger = require('logger'), + file = require('env!env/file'), + parse = require('parse'), + optimize = require('optimize'), + pragma = require('pragma'), + transform = require('transform'), + requirePatch = require('requirePatch'), + env = require('env'), + commonJs = require('commonJs'), + SourceMapGenerator = require('source-map').SourceMapGenerator, + hasProp = lang.hasProp, + getOwn = lang.getOwn, + falseProp = lang.falseProp, + endsWithSemiColonRegExp = /;\s*$/, + endsWithSlashRegExp = /[\/\\]$/, + resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/, + deepCopyProps = { + layer: true + }; + + //Deep copy a config object, but do not copy over the "layer" property, + //as it can be a deeply nested structure with a full requirejs context. + function copyConfig(obj) { + return lang.deeplikeCopy(obj, deepCopyProps); + } + + prim.nextTick = function (fn) { + fn(); + }; + + //Now map require to the outermost requirejs, now that we have + //local dependencies for this module. The rest of the require use is + //manipulating the requirejs loader. + require = requirejs; + + //Caching function for performance. Attached to + //require so it can be reused in requirePatch.js. _cachedRawText + //set up by requirePatch.js + require._cacheReadAsync = function (path, encoding) { + var d; + + if (lang.hasProp(require._cachedRawText, path)) { + d = prim(); + d.resolve(require._cachedRawText[path]); + return d.promise; + } else { + return file.readFileAsync(path, encoding).then(function (text) { + require._cachedRawText[path] = text; + return text; + }); + } + }; + + function makeBuildBaseConfig() { + return { + appDir: "", + pragmas: {}, + paths: {}, + optimize: "uglify", + optimizeCss: "standard.keepLines.keepWhitespace", + inlineText: true, + isBuild: true, + optimizeAllPluginResources: false, + findNestedDependencies: false, + preserveLicenseComments: true, + writeBuildTxt: true, + //Some builds can take a while, up the default limit. + waitSeconds: 30, + //By default, all files/directories are copied, unless + //they match this regexp, by default just excludes .folders + dirExclusionRegExp: file.dirExclusionRegExp, + _buildPathToModuleIndex: {} + }; + } + + /** + * Some JS may not be valid if concatenated with other JS, in particular + * the style of omitting semicolons and rely on ASI. Add a semicolon in + * those cases. + */ + function addSemiColon(text, config) { + if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) { + return text; + } else { + return text + ";"; + } + } + + function endsWithSlash(dirName) { + if (dirName.charAt(dirName.length - 1) !== "/") { + dirName += "/"; + } + return dirName; + } + + function endsWithNewLine(text) { + if (text.charAt(text.length - 1) !== "\n") { + text += "\n"; + } + return text; + } + + //Method used by plugin writeFile calls, defined up here to avoid + //jslint warning about "making a function in a loop". + function makeWriteFile(namespace, layer) { + function writeFile(name, contents) { + logger.trace('Saving plugin-optimized file: ' + name); + file.saveUtf8File(name, contents); + } + + writeFile.asModule = function (moduleName, fileName, contents) { + writeFile(fileName, + build.toTransport(namespace, moduleName, fileName, contents, layer)); + }; + + return writeFile; + } + + /** + * Appends singleContents to fileContents and returns the result. If a sourceMapGenerator + * is provided, adds singleContents to the source map. + * + * @param {string} fileContents - The file contents to which to append singleContents + * @param {string} singleContents - The additional contents to append to fileContents + * @param {string} path - An absolute path of a file whose name to use in the source map. + * The file need not actually exist if the code in singleContents is generated. + * @param {{out: ?string, baseUrl: ?string}} config - The build configuration object. + * @param {?{_buildPath: ?string}} module - An object with module information. + * @param {?SourceMapGenerator} sourceMapGenerator - An instance of Mozilla's SourceMapGenerator, + * or null if no source map is being generated. + * @returns {string} fileContents with singleContents appended + */ + function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) { + var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i; + if (sourceMapGenerator) { + if (config.out) { + refPath = config.baseUrl; + } else if (module && module._buildPath) { + refPath = module._buildPath; + } else { + refPath = ""; + } + parts = path.split('!'); + if (parts.length === 1) { + //Not a plugin resource, fix the path + sourceMapPath = build.makeRelativeFilePath(refPath, path); + } else { + //Plugin resource. If it looks like just a plugin + //followed by a module ID, pull off the plugin + //and put it at the end of the name, otherwise + //just leave it alone. + pluginId = parts.shift(); + resourcePath = parts.join('!'); + if (resourceIsModuleIdRegExp.test(resourcePath)) { + sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) + + '!' + pluginId; + } else { + sourceMapPath = path; + } + } + + sourceMapLineNumber = fileContents.split('\n').length - 1; + lineCount = singleContents.split('\n').length; + for (i = 1; i <= lineCount; i += 1) { + sourceMapGenerator.addMapping({ + generated: { + line: sourceMapLineNumber + i, + column: 0 + }, + original: { + line: i, + column: 0 + }, + source: sourceMapPath + }); + } + + //Store the content of the original in the source + //map since other transforms later like minification + //can mess up translating back to the original + //source. + sourceMapGenerator.setSourceContent(sourceMapPath, singleContents); + } + fileContents += singleContents; + return fileContents; + } + + /** + * Main API entry point into the build. The args argument can either be + * an array of arguments (like the onese passed on a command-line), + * or it can be a JavaScript object that has the format of a build profile + * file. + * + * If it is an object, then in addition to the normal properties allowed in + * a build profile file, the object should contain one other property: + * + * The object could also contain a "buildFile" property, which is a string + * that is the file path to a build profile that contains the rest + * of the build profile directives. + * + * This function does not return a status, it should throw an error if + * there is a problem completing the build. + */ + build = function (args) { + var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree, + i, j, errorMod, + stackRegExp = /( {4}at[^\n]+)\n/, + standardIndent = ' '; + + return prim().start(function () { + if (!args || lang.isArray(args)) { + if (!args || args.length < 1) { + logger.error("build.js buildProfile.js\n" + + "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file)."); + return undefined; + } + + //Next args can include a build file path as well as other build args. + //build file path comes first. If it does not contain an = then it is + //a build file path. Otherwise, just all build args. + if (args[0].indexOf("=") === -1) { + buildFile = args[0]; + args.splice(0, 1); + } + + //Remaining args are options to the build + cmdConfig = build.convertArrayToObject(args); + cmdConfig.buildFile = buildFile; + } else { + cmdConfig = args; + } + + return build._run(cmdConfig); + }).then(null, function (e) { + var err; + + errorMsg = e.toString(); + errorTree = e.moduleTree; + stackMatch = stackRegExp.exec(errorMsg); + + if (stackMatch) { + errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1); + } + + //If a module tree that shows what module triggered the error, + //print it out. + if (errorTree && errorTree.length > 0) { + errorMsg += '\nIn module tree:\n'; + + for (i = errorTree.length - 1; i > -1; i--) { + errorMod = errorTree[i]; + if (errorMod) { + for (j = errorTree.length - i; j > -1; j--) { + errorMsg += standardIndent; + } + errorMsg += errorMod + '\n'; + } + } + + logger.error(errorMsg); + } + + errorStack = e.stack; + + if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) { + errorMsg += '\n' + errorStack; + } else { + if (!stackMatch && errorStack) { + //Just trim out the first "at" in the stack. + stackMatch = stackRegExp.exec(errorStack); + if (stackMatch) { + errorMsg += '\n' + stackMatch[0] || ''; + } + } + } + + err = new Error(errorMsg); + err.originalError = e; + throw err; + }); + }; + + build._run = function (cmdConfig) { + var buildPaths, fileName, fileNames, + paths, i, + baseConfig, config, + modules, srcPath, buildContext, + destPath, moduleMap, parentModuleMap, context, + resources, resource, plugin, fileContents, + pluginProcessed = {}, + buildFileContents = "", + pluginCollector = {}; + + return prim().start(function () { + var prop; + + //Can now run the patches to require.js to allow it to be used for + //build generation. Do it here instead of at the top of the module + //because we want normal require behavior to load the build tool + //then want to switch to build mode. + requirePatch(); + + config = build.createConfig(cmdConfig); + paths = config.paths; + + //Remove the previous build dir, in case it contains source transforms, + //like the ones done with onBuildRead and onBuildWrite. + if (config.dir && !config.keepBuildDir && file.exists(config.dir)) { + file.deleteFile(config.dir); + } + + if (!config.out && !config.cssIn) { + //This is not just a one-off file build but a full build profile, with + //lots of files to process. + + //First copy all the baseUrl content + file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true); + + //Adjust baseUrl if config.appDir is in play, and set up build output paths. + buildPaths = {}; + if (config.appDir) { + //All the paths should be inside the appDir, so just adjust + //the paths to use the dirBaseUrl + for (prop in paths) { + if (hasProp(paths, prop)) { + buildPaths[prop] = paths[prop].replace(config.appDir, config.dir); + } + } + } else { + //If no appDir, then make sure to copy the other paths to this directory. + for (prop in paths) { + if (hasProp(paths, prop)) { + //Set up build path for each path prefix, but only do so + //if the path falls out of the current baseUrl + if (paths[prop].indexOf(config.baseUrl) === 0) { + buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl); + } else { + buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop; + + //Make sure source path is fully formed with baseUrl, + //if it is a relative URL. + srcPath = paths[prop]; + if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) { + srcPath = config.baseUrl + srcPath; + } + + destPath = config.dirBaseUrl + buildPaths[prop]; + + //Skip empty: paths + if (srcPath !== 'empty:') { + //If the srcPath is a directory, copy the whole directory. + if (file.exists(srcPath) && file.isDirectory(srcPath)) { + //Copy files to build area. Copy all files (the /\w/ regexp) + file.copyDir(srcPath, destPath, /\w/, true); + } else { + //Try a .js extension + srcPath += '.js'; + destPath += '.js'; + file.copyFile(srcPath, destPath); + } + } + } + } + } + } + } + + //Figure out source file location for each module layer. Do this by seeding require + //with source area configuration. This is needed so that later the module layers + //can be manually copied over to the source area, since the build may be + //require multiple times and the above copyDir call only copies newer files. + require({ + baseUrl: config.baseUrl, + paths: paths, + packagePaths: config.packagePaths, + packages: config.packages + }); + buildContext = require.s.contexts._; + modules = config.modules; + + if (modules) { + modules.forEach(function (module) { + if (module.name) { + module._sourcePath = buildContext.nameToUrl(module.name); + //If the module does not exist, and this is not a "new" module layer, + //as indicated by a true "create" property on the module, and + //it is not a plugin-loaded resource, and there is no + //'rawText' containing the module's source then throw an error. + if (!file.exists(module._sourcePath) && !module.create && + module.name.indexOf('!') === -1 && + (!config.rawText || !lang.hasProp(config.rawText, module.name))) { + throw new Error("ERROR: module path does not exist: " + + module._sourcePath + " for module named: " + module.name + + ". Path is relative to: " + file.absPath('.')); + } + } + }); + } + + if (config.out) { + //Just set up the _buildPath for the module layer. + require(config); + if (!config.cssIn) { + config.modules[0]._buildPath = typeof config.out === 'function' ? + 'FUNCTION' : config.out; + } + } else if (!config.cssIn) { + //Now set up the config for require to use the build area, and calculate the + //build file locations. Pass along any config info too. + baseConfig = { + baseUrl: config.dirBaseUrl, + paths: buildPaths + }; + + lang.mixin(baseConfig, config); + require(baseConfig); + + if (modules) { + modules.forEach(function (module) { + if (module.name) { + module._buildPath = buildContext.nameToUrl(module.name, null); + + //If buildPath and sourcePath are the same, throw since this + //would result in modifying source. This condition can happen + //with some more tricky paths: config and appDir/baseUrl + //setting, which is a sign of incorrect config. + if (module._buildPath === module._sourcePath && + !config.allowSourceOverwrites) { + throw new Error('Module ID \'' + module.name + + '\' has a source path that is same as output path: ' + + module._sourcePath + + '. Stopping, config is malformed.'); + } + + // Copy the file, but only if it is not provided in rawText. + if (!module.create && (!config.rawText || !lang.hasProp(config.rawText, module.name))) { + file.copyFile(module._sourcePath, module._buildPath); + } + } + }); + } + } + + //Run CSS optimizations before doing JS module tracing, to allow + //things like text loader plugins loading CSS to get the optimized + //CSS. + if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) { + buildFileContents += optimize.css(config.dir, config); + } + }).then(function() { + baseConfig = copyConfig(require.s.contexts._.config); + }).then(function () { + var actions = []; + + if (modules) { + actions = modules.map(function (module, i) { + return function () { + //Save off buildPath to module index in a hash for quicker + //lookup later. + config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i; + + //Call require to calculate dependencies. + return build.traceDependencies(module, config, baseConfig) + .then(function (layer) { + module.layer = layer; + }); + }; + }); + + return prim.serial(actions); + } + }).then(function () { + var actions; + + if (modules) { + //Now build up shadow layers for anything that should be excluded. + //Do this after tracing dependencies for each module, in case one + //of those modules end up being one of the excluded values. + actions = modules.map(function (module) { + return function () { + if (module.exclude) { + module.excludeLayers = []; + return prim.serial(module.exclude.map(function (exclude, i) { + return function () { + //See if it is already in the list of modules. + //If not trace dependencies for it. + var found = build.findBuildModule(exclude, modules); + if (found) { + module.excludeLayers[i] = found; + } else { + return build.traceDependencies({name: exclude}, config, baseConfig) + .then(function (layer) { + module.excludeLayers[i] = { layer: layer }; + }); + } + }; + })); + } + }; + }); + + return prim.serial(actions); + } + }).then(function () { + if (modules) { + return prim.serial(modules.map(function (module) { + return function () { + if (module.exclude) { + //module.exclude is an array of module names. For each one, + //get the nested dependencies for it via a matching entry + //in the module.excludeLayers array. + module.exclude.forEach(function (excludeModule, i) { + var excludeLayer = module.excludeLayers[i].layer, + map = excludeLayer.buildFileToModule; + excludeLayer.buildFilePaths.forEach(function(filePath){ + build.removeModulePath(map[filePath], filePath, module.layer); + }); + }); + } + if (module.excludeShallow) { + //module.excludeShallow is an array of module names. + //shallow exclusions are just that module itself, and not + //its nested dependencies. + module.excludeShallow.forEach(function (excludeShallowModule) { + var path = getOwn(module.layer.buildPathMap, excludeShallowModule); + if (path) { + build.removeModulePath(excludeShallowModule, path, module.layer); + } + }); + } + + //Flatten them and collect the build output for each module. + return build.flattenModule(module, module.layer, config).then(function (builtModule) { + var finalText, baseName; + //Save it to a temp file for now, in case there are other layers that + //contain optimized content that should not be included in later + //layer optimizations. See issue #56. + if (module._buildPath === 'FUNCTION') { + module._buildText = builtModule.text; + module._buildSourceMap = builtModule.sourceMap; + } else { + finalText = builtModule.text; + if (builtModule.sourceMap) { + baseName = module._buildPath.split('/'); + baseName = baseName.pop(); + finalText += '\n//# sourceMappingURL=' + baseName + '.map'; + file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap); + } + file.saveUtf8File(module._buildPath + '-temp', finalText); + + } + buildFileContents += builtModule.buildText; + }); + }; + })); + } + }).then(function () { + var moduleName, outOrigSourceMap, + bundlesConfig = {}, + bundlesConfigOutFile = config.bundlesConfigOutFile; + + if (modules) { + //Now move the build layers to their final position. + modules.forEach(function (module) { + var entryConfig, + finalPath = module._buildPath; + + if (finalPath !== 'FUNCTION') { + if (file.exists(finalPath)) { + file.deleteFile(finalPath); + } + file.renameFile(finalPath + '-temp', finalPath); + + //If bundles config should be written out, scan the + //built file for module IDs. Favor doing this reparse + //since tracking the IDs as the file is built has some + //edge cases around files that had more than one ID in + //them already, and likely loader plugin-written contents. + if (bundlesConfigOutFile) { + entryConfig = bundlesConfig[module.name] = []; + var bundleContents = file.readFile(finalPath); + var excludeMap = {}; + excludeMap[module.name] = true; + var parsedIds = parse.getAllNamedDefines(bundleContents, excludeMap); + entryConfig.push.apply(entryConfig, parsedIds); + } + + //And finally, if removeCombined is specified, remove + //any of the files that were used in this layer. + //Be sure not to remove other build layers. + if (config.removeCombined && !config.out) { + module.layer.buildFilePaths.forEach(function (path) { + var isLayer = modules.some(function (mod) { + return mod._buildPath === path; + }), + relPath = build.makeRelativeFilePath(config.dir, path); + + if (file.exists(path) && + // not a build layer target + !isLayer && + // not outside the build directory + relPath.indexOf('..') !== 0) { + file.deleteFile(path); + } + }); + } + } + + //Signal layer is done + if (config.onModuleBundleComplete) { + config.onModuleBundleComplete(module.onCompleteData); + } + }); + + //Write out bundles config, if it is wanted. + if (bundlesConfigOutFile) { + var text = file.readFile(bundlesConfigOutFile); + text = transform.modifyConfig(text, function (config) { + if (!config.bundles) { + config.bundles = {}; + } + + lang.eachProp(bundlesConfig, function (value, prop) { + config.bundles[prop] = value; + }); + + return config; + }); + + file.saveUtf8File(bundlesConfigOutFile, text); + } + } + + //If removeCombined in play, remove any empty directories that + //may now exist because of its use + if (config.removeCombined && !config.out && config.dir) { + file.deleteEmptyDirs(config.dir); + } + + //Do other optimizations. + if (config.out && !config.cssIn) { + //Just need to worry about one JS file. + fileName = config.modules[0]._buildPath; + if (fileName === 'FUNCTION') { + outOrigSourceMap = config.modules[0]._buildSourceMap; + config._buildSourceMap = outOrigSourceMap; + config.modules[0]._buildText = optimize.js((config.modules[0].name || + config.modules[0].include[0] || + fileName) + '.build.js', + config.modules[0]._buildText, + null, + config); + if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) { + config.modules[0]._buildSourceMap = config._buildSourceMap; + config._buildSourceMap = null; + } + } else { + optimize.jsFile(fileName, null, fileName, config); + } + } else if (!config.cssIn) { + //Normal optimizations across modules. + + //JS optimizations. + fileNames = file.getFilteredFileList(config.dir, /\.js$/, true); + fileNames.forEach(function (fileName) { + var cfg, override, moduleIndex; + + //Generate the module name from the config.dir root. + moduleName = fileName.replace(config.dir, ''); + //Get rid of the extension + moduleName = moduleName.substring(0, moduleName.length - 3); + + //If there is an override for a specific layer build module, + //and this file is that module, mix in the override for use + //by optimize.jsFile. + moduleIndex = getOwn(config._buildPathToModuleIndex, fileName); + //Normalize, since getOwn could have returned undefined + moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1; + + //Try to avoid extra work if the other files do not need to + //be read. Build layers should be processed at the very + //least for optimization. + if (moduleIndex > -1 || !config.skipDirOptimize || + config.normalizeDirDefines === "all" || + config.cjsTranslate) { + //Convert the file to transport format, but without a name + //inserted (by passing null for moduleName) since the files are + //standalone, one module per file. + fileContents = file.readFile(fileName); + + + //For builds, if wanting cjs translation, do it now, so that + //the individual modules can be loaded cross domain via + //plain script tags. + if (config.cjsTranslate && + (!config.shim || !lang.hasProp(config.shim, moduleName))) { + fileContents = commonJs.convert(fileName, fileContents); + } + + if (moduleIndex === -1) { + if (config.onBuildRead) { + fileContents = config.onBuildRead(moduleName, + fileName, + fileContents); + } + + //Only do transport normalization if this is not a build + //layer (since it was already normalized) and if + //normalizeDirDefines indicated all should be done. + if (config.normalizeDirDefines === "all") { + fileContents = build.toTransport(config.namespace, + null, + fileName, + fileContents); + } + + if (config.onBuildWrite) { + fileContents = config.onBuildWrite(moduleName, + fileName, + fileContents); + } + } + + override = moduleIndex > -1 ? + config.modules[moduleIndex].override : null; + if (override) { + cfg = build.createOverrideConfig(config, override); + } else { + cfg = config; + } + + if (moduleIndex > -1 || !config.skipDirOptimize) { + optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector); + } + } + }); + + //Normalize all the plugin resources. + context = require.s.contexts._; + + for (moduleName in pluginCollector) { + if (hasProp(pluginCollector, moduleName)) { + parentModuleMap = context.makeModuleMap(moduleName); + resources = pluginCollector[moduleName]; + for (i = 0; i < resources.length; i++) { + resource = resources[i]; + moduleMap = context.makeModuleMap(resource, parentModuleMap); + if (falseProp(context.plugins, moduleMap.prefix)) { + //Set the value in context.plugins so it + //will be evaluated as a full plugin. + context.plugins[moduleMap.prefix] = true; + + //Do not bother if the plugin is not available. + if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) { + continue; + } + + //Rely on the require in the build environment + //to be synchronous + context.require([moduleMap.prefix]); + + //Now that the plugin is loaded, redo the moduleMap + //since the plugin will need to normalize part of the path. + moduleMap = context.makeModuleMap(resource, parentModuleMap); + } + + //Only bother with plugin resources that can be handled + //processed by the plugin, via support of the writeFile + //method. + if (falseProp(pluginProcessed, moduleMap.id)) { + //Only do the work if the plugin was really loaded. + //Using an internal access because the file may + //not really be loaded. + plugin = getOwn(context.defined, moduleMap.prefix); + if (plugin && plugin.writeFile) { + plugin.writeFile( + moduleMap.prefix, + moduleMap.name, + require, + makeWriteFile( + config.namespace + ), + context.config + ); + } + + pluginProcessed[moduleMap.id] = true; + } + } + + } + } + + //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " ")); + + + //All module layers are done, write out the build.txt file. + if (config.writeBuildTxt) { + file.saveUtf8File(config.dir + "build.txt", buildFileContents); + } + } + + //If just have one CSS file to optimize, do that here. + if (config.cssIn) { + buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText; + } + + if (typeof config.out === 'function') { + config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap); + } + + //Print out what was built into which layers. + if (buildFileContents) { + logger.info(buildFileContents); + return buildFileContents; + } + + return ''; + }); + }; + + /** + * Converts command line args like "paths.foo=../some/path" + * result.paths = { foo: '../some/path' } where prop = paths, + * name = paths.foo and value = ../some/path, so it assumes the + * name=value splitting has already happened. + */ + function stringDotToObj(result, name, value) { + var parts = name.split('.'); + + parts.forEach(function (prop, i) { + if (i === parts.length - 1) { + result[prop] = value; + } else { + if (falseProp(result, prop)) { + result[prop] = {}; + } + result = result[prop]; + } + + }); + } + + build.objProps = { + paths: true, + wrap: true, + pragmas: true, + pragmasOnSave: true, + has: true, + hasOnSave: true, + uglify: true, + uglify2: true, + closure: true, + map: true, + throwWhen: true + }; + + build.hasDotPropMatch = function (prop) { + var dotProp, + index = prop.indexOf('.'); + + if (index !== -1) { + dotProp = prop.substring(0, index); + return hasProp(build.objProps, dotProp); + } + return false; + }; + + /** + * Converts an array that has String members of "name=value" + * into an object, where the properties on the object are the names in the array. + * Also converts the strings "true" and "false" to booleans for the values. + * member name/value pairs, and converts some comma-separated lists into + * arrays. + * @param {Array} ary + */ + build.convertArrayToObject = function (ary) { + var result = {}, i, separatorIndex, prop, value, + needArray = { + "include": true, + "exclude": true, + "excludeShallow": true, + "insertRequire": true, + "stubModules": true, + "deps": true, + "mainConfigFile": true, + "wrap.startFile": true, + "wrap.endFile": true + }; + + for (i = 0; i < ary.length; i++) { + separatorIndex = ary[i].indexOf("="); + if (separatorIndex === -1) { + throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value"; + } + + value = ary[i].substring(separatorIndex + 1, ary[i].length); + if (value === "true") { + value = true; + } else if (value === "false") { + value = false; + } + + prop = ary[i].substring(0, separatorIndex); + + //Convert to array if necessary + if (getOwn(needArray, prop)) { + value = value.split(","); + } + + if (build.hasDotPropMatch(prop)) { + stringDotToObj(result, prop, value); + } else { + result[prop] = value; + } + } + return result; //Object + }; + + build.makeAbsPath = function (path, absFilePath) { + if (!absFilePath) { + return path; + } + + //Add abspath if necessary. If path starts with a slash or has a colon, + //then already is an abolute path. + if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) { + path = absFilePath + + (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') + + path; + path = file.normalize(path); + } + return path.replace(lang.backSlashRegExp, '/'); + }; + + build.makeAbsObject = function (props, obj, absFilePath) { + var i, prop; + if (obj) { + for (i = 0; i < props.length; i++) { + prop = props[i]; + if (hasProp(obj, prop) && typeof obj[prop] === 'string') { + obj[prop] = build.makeAbsPath(obj[prop], absFilePath); + } + } + } + }; + + /** + * For any path in a possible config, make it absolute relative + * to the absFilePath passed in. + */ + build.makeAbsConfig = function (config, absFilePath) { + var props, prop, i; + + props = ["appDir", "dir", "baseUrl"]; + for (i = 0; i < props.length; i++) { + prop = props[i]; + + if (getOwn(config, prop)) { + //Add abspath if necessary, make sure these paths end in + //slashes + if (prop === "baseUrl") { + config.originalBaseUrl = config.baseUrl; + if (config.appDir) { + //If baseUrl with an appDir, the baseUrl is relative to + //the appDir, *not* the absFilePath. appDir and dir are + //made absolute before baseUrl, so this will work. + config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir); + } else { + //The dir output baseUrl is same as regular baseUrl, both + //relative to the absFilePath. + config.baseUrl = build.makeAbsPath(config[prop], absFilePath); + } + } else { + config[prop] = build.makeAbsPath(config[prop], absFilePath); + } + + config[prop] = endsWithSlash(config[prop]); + } + } + + build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]), + config, absFilePath); + build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath); + build.makeAbsObject(["externExportsPath"], config.closure, absFilePath); + }; + + /** + * Creates a relative path to targetPath from refPath. + * Only deals with file paths, not folders. If folders, + * make sure paths end in a trailing '/'. + */ + build.makeRelativeFilePath = function (refPath, targetPath) { + var i, dotLength, finalParts, length, targetParts, targetName, + refParts = refPath.split('/'), + hasEndSlash = endsWithSlashRegExp.test(targetPath), + dotParts = []; + + targetPath = file.normalize(targetPath); + if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) { + targetPath += '/'; + } + targetParts = targetPath.split('/'); + //Pull off file name + targetName = targetParts.pop(); + + //Also pop off the ref file name to make the matches against + //targetParts equivalent. + refParts.pop(); + + length = refParts.length; + + for (i = 0; i < length; i += 1) { + if (refParts[i] !== targetParts[i]) { + break; + } + } + + //Now i is the index in which they diverge. + finalParts = targetParts.slice(i); + + dotLength = length - i; + for (i = 0; i > -1 && i < dotLength; i += 1) { + dotParts.push('..'); + } + + return dotParts.join('/') + (dotParts.length ? '/' : '') + + finalParts.join('/') + (finalParts.length ? '/' : '') + + targetName; + }; + + build.nestedMix = { + paths: true, + has: true, + hasOnSave: true, + pragmas: true, + pragmasOnSave: true + }; + + /** + * Mixes additional source config into target config, and merges some + * nested config, like paths, correctly. + */ + function mixConfig(target, source, skipArrays) { + var prop, value, isArray, targetValue; + + for (prop in source) { + if (hasProp(source, prop)) { + //If the value of the property is a plain object, then + //allow a one-level-deep mixing of it. + value = source[prop]; + isArray = lang.isArray(value); + if (typeof value === 'object' && value && + !isArray && !lang.isFunction(value) && + !lang.isRegExp(value)) { + + // TODO: need to generalize this work, maybe also reuse + // the work done in requirejs configure, perhaps move to + // just a deep copy/merge overall. However, given the + // amount of observable change, wait for a dot release. + // This change is in relation to #645 + if (prop === 'map') { + if (!target.map) { + target.map = {}; + } + lang.deepMix(target.map, source.map); + } else { + target[prop] = lang.mixin({}, target[prop], value, true); + } + } else if (isArray) { + if (!skipArrays) { + // Some config, like packages, are arrays. For those, + // just merge the results. + targetValue = target[prop]; + if (lang.isArray(targetValue)) { + target[prop] = targetValue.concat(value); + } else { + target[prop] = value; + } + } + } else { + target[prop] = value; + } + } + } + + //Set up log level since it can affect if errors are thrown + //or caught and passed to errbacks while doing config setup. + if (lang.hasProp(target, 'logLevel')) { + logger.logLevel(target.logLevel); + } + } + + /** + * Converts a wrap.startFile or endFile to be start/end as a string. + * the startFile/endFile values can be arrays. + */ + function flattenWrapFile(config, keyName, absFilePath) { + var wrap = config.wrap, + keyFileName = keyName + 'File', + keyMapName = '__' + keyName + 'Map'; + + if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) { + wrap[keyName] = ''; + if (typeof wrap[keyFileName] === 'string') { + wrap[keyFileName] = [wrap[keyFileName]]; + } + wrap[keyMapName] = []; + wrap[keyFileName].forEach(function (fileName) { + var absPath = build.makeAbsPath(fileName, absFilePath), + fileText = endsWithNewLine(file.readFile(absPath)); + wrap[keyMapName].push(function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, fileText, absPath, cfg, null, sourceMapGenerator); + }); + wrap[keyName] += fileText; + }); + } else if (wrap[keyName] === null || wrap[keyName] === undefined) { + //Allow missing one, just set to empty string. + wrap[keyName] = ''; + } else if (typeof wrap[keyName] === 'string') { + wrap[keyName] = endsWithNewLine(wrap[keyName]); + wrap[keyMapName] = [ + function (fileContents, cfg, sourceMapGenerator) { + var absPath = build.makeAbsPath("config-wrap-" + keyName + "-default.js", absFilePath); + return appendToFileContents(fileContents, wrap[keyName], absPath, cfg, null, sourceMapGenerator); + } + ]; + } else { + throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed'); + } + } + + function normalizeWrapConfig(config, absFilePath) { + //Get any wrap text. + try { + if (config.wrap) { + if (config.wrap === true) { + //Use default values. + config.wrap = { + start: '(function () {\n', + end: '}());', + __startMap: [ + function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, "(function () {\n", + build.makeAbsPath("config-wrap-start-default.js", + absFilePath), cfg, null, + sourceMapGenerator); + } + ], + __endMap: [ + function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, "}());", + build.makeAbsPath("config-wrap-end-default.js", absFilePath), + cfg, null, sourceMapGenerator); + } + ] + }; + } else { + flattenWrapFile(config, 'start', absFilePath); + flattenWrapFile(config, 'end', absFilePath); + } + } + } catch (wrapError) { + throw new Error('Malformed wrap config: ' + wrapError.toString()); + } + } + + /** + * Creates a config object for an optimization build. + * It will also read the build profile if it is available, to create + * the configuration. + * + * @param {Object} cfg config options that take priority + * over defaults and ones in the build file. These options could + * be from a command line, for instance. + * + * @param {Object} the created config object. + */ + build.createConfig = function (cfg) { + /*jslint evil: true */ + var buildFileContents, buildFileConfig, mainConfig, + mainConfigFile, mainConfigPath, buildFile, absFilePath, + config = {}, + buildBaseConfig = makeBuildBaseConfig(); + + //Make sure all paths are relative to current directory. + absFilePath = file.absPath('.'); + build.makeAbsConfig(cfg, absFilePath); + build.makeAbsConfig(buildBaseConfig, absFilePath); + + lang.mixin(config, buildBaseConfig); + lang.mixin(config, cfg, true); + + //Set up log level early since it can affect if errors are thrown + //or caught and passed to errbacks, even while constructing config. + if (lang.hasProp(config, 'logLevel')) { + logger.logLevel(config.logLevel); + } + + if (config.buildFile) { + //A build file exists, load it to get more config. + buildFile = file.absPath(config.buildFile); + + //Find the build file, and make sure it exists, if this is a build + //that has a build profile, and not just command line args with an in=path + if (!file.exists(buildFile)) { + throw new Error("ERROR: build file does not exist: " + buildFile); + } + + absFilePath = config.baseUrl = file.absPath(file.parent(buildFile)); + + //Load build file options. + buildFileContents = file.readFile(buildFile); + try { + //Be a bit lenient in the file ending in a ; or ending with + //a //# sourceMappingUrl comment, mostly for compiled languages + //that create a config, like typescript. + buildFileContents = buildFileContents + .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '') + .trim() + .replace(/;$/, ''); + + buildFileConfig = eval("(" + buildFileContents + ")"); + build.makeAbsConfig(buildFileConfig, absFilePath); + + //Mix in the config now so that items in mainConfigFile can + //be resolved relative to them if necessary, like if appDir + //is set here, but the baseUrl is in mainConfigFile. Will + //re-mix in the same build config later after mainConfigFile + //is processed, since build config should take priority. + mixConfig(config, buildFileConfig); + } catch (e) { + throw new Error("Build file " + buildFile + " is malformed: " + e); + } + } + + mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile); + if (mainConfigFile) { + if (typeof mainConfigFile === 'string') { + mainConfigFile = [mainConfigFile]; + } + + mainConfigFile.forEach(function (configFile) { + configFile = build.makeAbsPath(configFile, absFilePath); + if (!file.exists(configFile)) { + throw new Error(configFile + ' does not exist.'); + } + try { + mainConfig = parse.findConfig(file.readFile(configFile)).config; + } catch (configError) { + throw new Error('The config in mainConfigFile ' + + configFile + + ' cannot be used because it cannot be evaluated' + + ' correctly while running in the optimizer. Try only' + + ' using a config that is also valid JSON, or do not use' + + ' mainConfigFile and instead copy the config values needed' + + ' into a build file or command line arguments given to the optimizer.\n' + + 'Source error from parsing: ' + configFile + ': ' + configError); + } + if (mainConfig) { + mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/')); + + //Add in some existing config, like appDir, since they can be + //used inside the configFile -- paths and baseUrl are + //relative to them. + if (config.appDir && !mainConfig.appDir) { + mainConfig.appDir = config.appDir; + } + + //If no baseUrl, then use the directory holding the main config. + if (!mainConfig.baseUrl) { + mainConfig.baseUrl = mainConfigPath; + } + + build.makeAbsConfig(mainConfig, mainConfigPath); + mixConfig(config, mainConfig); + } + }); + } + + //Mix in build file config, but only after mainConfig has been mixed in. + //Since this is a re-application, skip array merging. + if (buildFileConfig) { + mixConfig(config, buildFileConfig, true); + } + + //Re-apply the override config values. Command line + //args should take precedence over build file values. + //Since this is a re-application, skip array merging. + mixConfig(config, cfg, true); + + //Fix paths to full paths so that they can be adjusted consistently + //lately to be in the output area. + lang.eachProp(config.paths, function (value, prop) { + if (lang.isArray(value)) { + throw new Error('paths fallback not supported in optimizer. ' + + 'Please provide a build config path override ' + + 'for ' + prop); + } + config.paths[prop] = build.makeAbsPath(value, config.baseUrl); + }); + + //Set final output dir + if (hasProp(config, "baseUrl")) { + if (config.appDir) { + if (!config.originalBaseUrl) { + throw new Error('Please set a baseUrl in the build config'); + } + config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir); + } else { + config.dirBaseUrl = config.dir || config.baseUrl; + } + //Make sure dirBaseUrl ends in a slash, since it is + //concatenated with other strings. + config.dirBaseUrl = endsWithSlash(config.dirBaseUrl); + } + + if (config.bundlesConfigOutFile) { + if (!config.dir) { + throw new Error('bundlesConfigOutFile can only be used with optimizations ' + + 'that use "dir".'); + } + config.bundlesConfigOutFile = build.makeAbsPath(config.bundlesConfigOutFile, config.dir); + } + + //If out=stdout, write output to STDOUT instead of a file. + if (config.out && config.out === 'stdout') { + config.out = function (content) { + var e = env.get(); + if (e === 'rhino') { + var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8'); + out.println(content); + } else if (e === 'node') { + process.stdout.write(content, 'utf8'); + } else { + console.log(content); + } + }; + } + + //Check for errors in config + if (config.main) { + throw new Error('"main" passed as an option, but the ' + + 'supported option is called "name".'); + } + if (config.out && !config.name && !config.modules && !config.include && + !config.cssIn) { + throw new Error('Missing either a "name", "include" or "modules" ' + + 'option'); + } + if (config.cssIn) { + if (config.dir || config.appDir) { + throw new Error('cssIn is only for the output of single file ' + + 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.'); + } + if (!config.out) { + throw new Error('"out" option missing.'); + } + } + if (!config.cssIn && !config.baseUrl) { + //Just use the current directory as the baseUrl + config.baseUrl = './'; + } + if (!config.out && !config.dir) { + throw new Error('Missing either an "out" or "dir" config value. ' + + 'If using "appDir" for a full project optimization, ' + + 'use "dir". If you want to optimize to one file, ' + + 'use "out".'); + } + if (config.appDir && config.out) { + throw new Error('"appDir" is not compatible with "out". Use "dir" ' + + 'instead. appDir is used to copy whole projects, ' + + 'where "out" with "baseUrl" is used to just ' + + 'optimize to one file.'); + } + if (config.out && config.dir) { + throw new Error('The "out" and "dir" options are incompatible.' + + ' Use "out" if you are targeting a single file' + + ' for optimization, and "dir" if you want the appDir' + + ' or baseUrl directories optimized.'); + } + + + if (config.dir) { + // Make sure the output dir is not set to a parent of the + // source dir or the same dir, as it will result in source + // code deletion. + if (!config.allowSourceOverwrites && (config.dir === config.baseUrl || + config.dir === config.appDir || + (config.baseUrl && build.makeRelativeFilePath(config.dir, + config.baseUrl).indexOf('..') !== 0) || + (config.appDir && + build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) { + throw new Error('"dir" is set to a parent or same directory as' + + ' "appDir" or "baseUrl". This can result in' + + ' the deletion of source code. Stopping. If' + + ' you want to allow possible overwriting of' + + ' source code, set "allowSourceOverwrites"' + + ' to true in the build config, but do so at' + + ' your own risk. In that case, you may want' + + ' to also set "keepBuildDir" to true.'); + } + } + + if (config.insertRequire && !lang.isArray(config.insertRequire)) { + throw new Error('insertRequire should be a list of module IDs' + + ' to insert in to a require([]) call.'); + } + + //Support older configs with uglify2 settings, but now that uglify1 has + //been removed, just translate it to 'uglify' settings. + if (config.optimize === 'uglify2') { + config.optimize = 'uglify'; + } + if (config.uglify2) { + config.uglify = config.uglify2; + delete config.uglify2; + } + + if (config.generateSourceMaps) { + if (config.preserveLicenseComments && !(config.optimize === 'none' || config.optimize === 'uglify')) { + throw new Error('Cannot use preserveLicenseComments and ' + + 'generateSourceMaps together, unless optimize is set ' + + 'to \'uglify\'. Either explicitly set preserveLicenseComments ' + + 'to false (default is true) or turn off generateSourceMaps. ' + + 'If you want source maps with license comments, see: ' + + 'http://requirejs.org/docs/errors.html#sourcemapcomments'); + } else if (config.optimize !== 'none' && + config.optimize !== 'closure' && + config.optimize !== 'uglify') { + //Allow optimize: none to pass, since it is useful when toggling + //minification on and off to debug something, and it implicitly + //works, since it does not need a source map. + throw new Error('optimize: "' + config.optimize + + '" does not support generateSourceMaps.'); + } + } + + if ((config.name || config.include) && !config.modules) { + //Just need to build one file, but may be part of a whole appDir/ + //baseUrl copy, but specified on the command line, so cannot do + //the modules array setup. So create a modules section in that + //case. + config.modules = [ + { + name: config.name, + out: config.out, + create: config.create, + include: config.include, + exclude: config.exclude, + excludeShallow: config.excludeShallow, + insertRequire: config.insertRequire, + stubModules: config.stubModules + } + ]; + delete config.stubModules; + } else if (config.modules && config.out) { + throw new Error('If the "modules" option is used, then there ' + + 'should be a "dir" option set and "out" should ' + + 'not be used since "out" is only for single file ' + + 'optimization output.'); + } else if (config.modules && config.name) { + throw new Error('"name" and "modules" options are incompatible. ' + + 'Either use "name" if doing a single file ' + + 'optimization, or "modules" if you want to target ' + + 'more than one file for optimization.'); + } + + if (config.out && !config.cssIn) { + //Just one file to optimize. + + //Does not have a build file, so set up some defaults. + //Optimizing CSS should not be allowed, unless explicitly + //asked for on command line. In that case the only task is + //to optimize a CSS file. + if (!cfg.optimizeCss) { + config.optimizeCss = "none"; + } + } + + //Normalize cssPrefix + if (config.cssPrefix) { + //Make sure cssPrefix ends in a slash + config.cssPrefix = endsWithSlash(config.cssPrefix); + } else { + config.cssPrefix = ''; + } + + //Cycle through modules and normalize + if (config.modules && config.modules.length) { + config.modules.forEach(function (mod) { + if (lang.isArray(mod) || typeof mod === 'string' || !mod) { + throw new Error('modules config item is malformed: it should' + + ' be an object with a \'name\' property.'); + } + + //Combine any local stubModules with global values. + if (config.stubModules) { + mod.stubModules = config.stubModules.concat(mod.stubModules || []); + } + + //Create a hash lookup for the stubModules config to make lookup + //cheaper later. + if (mod.stubModules) { + mod.stubModules._byName = {}; + mod.stubModules.forEach(function (id) { + mod.stubModules._byName[id] = true; + }); + } + + // Legacy command support, which allowed a single string ID + // for include. + if (typeof mod.include === 'string') { + mod.include = [mod.include]; + } + + //Allow wrap config in overrides, but normalize it. + if (mod.override) { + normalizeWrapConfig(mod.override, absFilePath); + } + }); + } + + normalizeWrapConfig(config, absFilePath); + + //Do final input verification + if (config.context) { + throw new Error('The build argument "context" is not supported' + + ' in a build. It should only be used in web' + + ' pages.'); + } + + //Set up normalizeDirDefines. If not explicitly set, if optimize "none", + //set to "skip" otherwise set to "all". + if (!hasProp(config, 'normalizeDirDefines')) { + if (config.optimize === 'none' || config.skipDirOptimize) { + config.normalizeDirDefines = 'skip'; + } else { + config.normalizeDirDefines = 'all'; + } + } + + //Set file.fileExclusionRegExp if desired + if (hasProp(config, 'fileExclusionRegExp')) { + if (typeof config.fileExclusionRegExp === "string") { + file.exclusionRegExp = new RegExp(config.fileExclusionRegExp); + } else { + file.exclusionRegExp = config.fileExclusionRegExp; + } + } else if (hasProp(config, 'dirExclusionRegExp')) { + //Set file.dirExclusionRegExp if desired, this is the old + //name for fileExclusionRegExp before 1.0.2. Support for backwards + //compatibility + file.exclusionRegExp = config.dirExclusionRegExp; + } + + //Track the deps, but in a different key, so that they are not loaded + //as part of config seeding before all config is in play (#648). Was + //going to merge this in with "include", but include is added after + //the "name" target. To preserve what r.js has done previously, make + //sure "deps" comes before the "name". + if (config.deps) { + config._depsInclude = config.deps; + } + + + //Remove things that may cause problems in the build. + //deps already merged above + delete config.deps; + delete config.jQuery; + delete config.enforceDefine; + delete config.urlArgs; + + return config; + }; + + /** + * finds the module being built/optimized with the given moduleName, + * or returns null. + * @param {String} moduleName + * @param {Array} modules + * @returns {Object} the module object from the build profile, or null. + */ + build.findBuildModule = function (moduleName, modules) { + var i, module; + for (i = 0; i < modules.length; i++) { + module = modules[i]; + if (module.name === moduleName) { + return module; + } + } + return null; + }; + + /** + * Removes a module name and path from a layer, if it is supposed to be + * excluded from the layer. + * @param {String} moduleName the name of the module + * @param {String} path the file path for the module + * @param {Object} layer the layer to remove the module/path from + */ + build.removeModulePath = function (module, path, layer) { + var index = layer.buildFilePaths.indexOf(path); + if (index !== -1) { + layer.buildFilePaths.splice(index, 1); + } + }; + + /** + * Uses the module build config object to trace the dependencies for the + * given module. + * + * @param {Object} module the module object from the build config info. + * @param {Object} config the build config object. + * @param {Object} [baseLoaderConfig] the base loader config to use for env resets. + * + * @returns {Object} layer information about what paths and modules should + * be in the flattened module. + */ + build.traceDependencies = function (module, config, baseLoaderConfig) { + var include, override, layer, context, oldContext, + rawTextByIds, + syncChecks = { + rhino: true, + node: true, + xpconnect: true + }, + deferred = prim(); + + //Reset some state set up in requirePatch.js, and clean up require's + //current context. + oldContext = require._buildReset(); + + //Grab the reset layer and context after the reset, but keep the + //old config to reuse in the new context. + layer = require._layer; + context = layer.context; + + //Put back basic config, use a fresh object for it. + if (baseLoaderConfig) { + require(copyConfig(baseLoaderConfig)); + } + + logger.trace("\nTracing dependencies for: " + (module.name || + (typeof module.out === 'function' ? 'FUNCTION' : module.out))); + include = config._depsInclude || []; + include = include.concat(module.name && !module.create ? [module.name] : []); + if (module.include) { + include = include.concat(module.include); + } + + //If there are overrides to basic config, set that up now.; + if (module.override) { + if (baseLoaderConfig) { + override = build.createOverrideConfig(baseLoaderConfig, module.override); + } else { + override = copyConfig(module.override); + } + require(override); + } + + //Now, populate the rawText cache with any values explicitly passed in + //via config. + rawTextByIds = require.s.contexts._.config.rawText; + if (rawTextByIds) { + lang.eachProp(rawTextByIds, function (contents, id) { + var url = require.toUrl(id) + '.js'; + require._cachedRawText[url] = contents; + }); + } + + + //Configure the callbacks to be called. + deferred.reject.__requireJsBuild = true; + + //Use a wrapping function so can check for errors. + function includeFinished(value) { + //If a sync build environment, check for errors here, instead of + //in the then callback below, since some errors, like two IDs pointed + //to same URL but only one anon ID will leave the loader in an + //unresolved state since a setTimeout cannot be used to check for + //timeout. + var hasError = false; + if (syncChecks[env.get()]) { + try { + build.checkForErrors(context, layer); + } catch (e) { + hasError = true; + deferred.reject(e); + } + } + + if (!hasError) { + deferred.resolve(value); + } + } + includeFinished.__requireJsBuild = true; + + //Figure out module layer dependencies by calling require to do the work. + require(include, includeFinished, deferred.reject); + + // If a sync env, then with the "two IDs to same anon module path" + // issue, the require never completes, need to check for errors + // here. + if (syncChecks[env.get()]) { + build.checkForErrors(context, layer); + } + + return deferred.promise.then(function () { + //Reset config + if (module.override && baseLoaderConfig) { + require(copyConfig(baseLoaderConfig)); + } + + build.checkForErrors(context, layer); + + return layer; + }); + }; + + build.checkForErrors = function (context, layer) { + //Check to see if it all loaded. If not, then throw, and give + //a message on what is left. + var id, prop, mod, idParts, pluginId, pluginResources, + errMessage = '', + failedPluginMap = {}, + failedPluginIds = [], + errIds = [], + errUrlMap = {}, + errUrlConflicts = {}, + hasErrUrl = false, + hasUndefined = false, + defined = context.defined, + registry = context.registry; + + function populateErrUrlMap(id, errUrl, skipNew) { + // Loader plugins do not have an errUrl, so skip them. + if (!errUrl) { + return; + } + + if (!skipNew) { + errIds.push(id); + } + + if (errUrlMap[errUrl]) { + hasErrUrl = true; + //This error module has the same URL as another + //error module, could be misconfiguration. + if (!errUrlConflicts[errUrl]) { + errUrlConflicts[errUrl] = []; + //Store the original module that had the same URL. + errUrlConflicts[errUrl].push(errUrlMap[errUrl]); + } + errUrlConflicts[errUrl].push(id); + } else if (!skipNew) { + errUrlMap[errUrl] = id; + } + } + + for (id in registry) { + if (hasProp(registry, id) && id.indexOf('_@r') !== 0) { + hasUndefined = true; + mod = getOwn(registry, id); + idParts = id.split('!'); + pluginId = idParts[0]; + + if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) { + populateErrUrlMap(id, mod.map.url); + } + + //Look for plugins that did not call load() + //But skip plugin IDs that were already inlined and called + //define() with a name. + if (!hasProp(layer.modulesWithNames, id) && idParts.length > 1) { + if (falseProp(failedPluginMap, pluginId)) { + failedPluginIds.push(pluginId); + } + pluginResources = failedPluginMap[pluginId]; + if (!pluginResources) { + pluginResources = failedPluginMap[pluginId] = []; + } + pluginResources.push(id + (mod.error ? ': ' + mod.error : '')); + } + } + } + + // If have some modules that are not defined/stuck in the registry, + // then check defined modules for URL overlap. + if (hasUndefined) { + for (id in defined) { + if (hasProp(defined, id) && id.indexOf('!') === -1) { + populateErrUrlMap(id, require.toUrl(id) + '.js', true); + } + } + } + + if (errIds.length || failedPluginIds.length) { + if (failedPluginIds.length) { + errMessage += 'Loader plugin' + + (failedPluginIds.length === 1 ? '' : 's') + + ' did not call ' + + 'the load callback in the build:\n' + + failedPluginIds.map(function (pluginId) { + var pluginResources = failedPluginMap[pluginId]; + return pluginId + ':\n ' + pluginResources.join('\n '); + }).join('\n') + '\n'; + } + errMessage += 'Module loading did not complete for: ' + errIds.join(', '); + + if (hasErrUrl) { + errMessage += '\nThe following modules share the same URL. This ' + + 'could be a misconfiguration if that URL only has ' + + 'one anonymous module in it:'; + for (prop in errUrlConflicts) { + if (hasProp(errUrlConflicts, prop)) { + errMessage += '\n' + prop + ': ' + + errUrlConflicts[prop].join(', '); + } + } + } + throw new Error(errMessage); + } + }; + + build.createOverrideConfig = function (config, override) { + var cfg = copyConfig(config), + oride = copyConfig(override); + + lang.eachProp(oride, function (value, prop) { + if (hasProp(build.objProps, prop)) { + //An object property, merge keys. Start a new object + //so that source object in config does not get modified. + cfg[prop] = {}; + lang.mixin(cfg[prop], config[prop], true); + lang.mixin(cfg[prop], override[prop], true); + } else { + cfg[prop] = override[prop]; + } + }); + + return cfg; + }; + + /** + * Uses the module build config object to create an flattened version + * of the module, with deep dependencies included. + * + * @param {Object} module the module object from the build config info. + * + * @param {Object} layer the layer object returned from build.traceDependencies. + * + * @param {Object} the build config object. + * + * @returns {Object} with two properties: "text", the text of the flattened + * module, and "buildText", a string of text representing which files were + * included in the flattened module text. + */ + build.flattenModule = function (module, layer, config) { + var fileContents, sourceMapGenerator, + sourceMapBase, + buildFileContents = ''; + + return prim().start(function () { + var reqIndex, currContents, fileForSourceMap, + moduleName, shim, packageName, + parts, builder, writeApi, + namespace, namespaceWithDot, stubModulesByName, + context = layer.context, + onLayerEnds = [], + onLayerEndAdded = {}, + pkgsMainMap = {}; + + //Use override settings, particularly for pragmas + //Do this before the var readings since it reads config values. + if (module.override) { + config = build.createOverrideConfig(config, module.override); + } + + namespace = config.namespace || ''; + namespaceWithDot = namespace ? namespace + '.' : ''; + stubModulesByName = (module.stubModules && module.stubModules._byName) || {}; + + //Start build output for the module. + module.onCompleteData = { + name: module.name, + path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath), + included: [] + }; + + buildFileContents += "\n" + + module.onCompleteData.path + + "\n----------------\n"; + + //If there was an existing file with require in it, hoist to the top. + if (layer.existingRequireUrl) { + reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl); + if (reqIndex !== -1) { + layer.buildFilePaths.splice(reqIndex, 1); + layer.buildFilePaths.unshift(layer.existingRequireUrl); + } + } + + if (config.generateSourceMaps) { + sourceMapBase = config.dir || config.baseUrl; + if (module._buildPath === 'FUNCTION') { + fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js'; + } else if (config.out) { + fileForSourceMap = module._buildPath.split('/').pop(); + } else { + fileForSourceMap = module._buildPath.replace(sourceMapBase, ''); + } + sourceMapGenerator = new SourceMapGenerator({ + file: fileForSourceMap + }); + } + + //Create a reverse lookup for packages main module IDs to their package + //names, useful for knowing when to write out define() package main ID + //adapters. + lang.eachProp(layer.context.config.pkgs, function(value, prop) { + pkgsMainMap[value] = prop; + }); + + //Write the built module to disk, and build up the build output. + fileContents = ""; + if (config.wrap && config.wrap.__startMap) { + config.wrap.__startMap.forEach(function (wrapFunction) { + fileContents = wrapFunction(fileContents, config, sourceMapGenerator); + }); + } + + return prim.serial(layer.buildFilePaths.map(function (path) { + return function () { + var singleContents = ''; + + moduleName = layer.buildFileToModule[path]; + + //If the moduleName is a package main, then hold on to the + //packageName in case an adapter needs to be written. + packageName = getOwn(pkgsMainMap, moduleName); + + return prim().start(function () { + //Figure out if the module is a result of a build plugin, and if so, + //then delegate to that plugin. + parts = context.makeModuleMap(moduleName); + builder = parts.prefix && getOwn(context.defined, parts.prefix); + if (builder) { + if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) { + onLayerEnds.push(builder); + onLayerEndAdded[parts.prefix] = true; + } + + if (builder.write) { + writeApi = function (input) { + singleContents += "\n" + addSemiColon(input, config); + if (config.onBuildWrite) { + singleContents = config.onBuildWrite(moduleName, path, singleContents); + } + }; + writeApi.asModule = function (moduleName, input) { + singleContents += "\n" + + addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, { + useSourceUrl: layer.context.config.useSourceUrl + }), config); + if (config.onBuildWrite) { + singleContents = config.onBuildWrite(moduleName, path, singleContents); + } + }; + builder.write(parts.prefix, parts.name, writeApi); + } + return; + } else { + return prim().start(function () { + if (hasProp(stubModulesByName, moduleName)) { + //Just want to insert a simple module definition instead + //of the source module. Useful for plugins that inline + //all their resources. + if (hasProp(layer.context.plugins, moduleName)) { + //Slightly different content for plugins, to indicate + //that dynamic loading will not work. + return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});'; + } else { + return 'define({});'; + } + } else { + return require._cacheReadAsync(path); + } + }).then(function (text) { + var hasPackageName; + + currContents = text; + + if (config.cjsTranslate && + (!config.shim || !lang.hasProp(config.shim, moduleName))) { + currContents = commonJs.convert(path, currContents); + } + + if (config.onBuildRead) { + currContents = config.onBuildRead(moduleName, path, currContents); + } + + if (packageName) { + hasPackageName = (packageName === parse.getNamedDefine(currContents)); + } + + if (namespace) { + currContents = pragma.namespace(currContents, namespace); + } + + currContents = build.toTransport(namespace, moduleName, path, currContents, layer, { + useSourceUrl: config.useSourceUrl + }); + + if (packageName && !hasPackageName) { + currContents = addSemiColon(currContents, config) + '\n'; + currContents += namespaceWithDot + "define('" + + packageName + "', ['" + moduleName + + "'], function (main) { return main; });\n"; + } + + if (config.onBuildWrite) { + currContents = config.onBuildWrite(moduleName, path, currContents); + } + + //Semicolon is for files that are not well formed when + //concatenated with other content. + singleContents += addSemiColon(currContents, config); + }); + } + }).then(function () { + var shimDeps, shortPath = path.replace(config.dir, ""); + + module.onCompleteData.included.push(shortPath); + buildFileContents += shortPath + "\n"; + + //Some files may not have declared a require module, and if so, + //put in a placeholder call so the require does not try to load them + //after the module is processed. + //If we have a name, but no defined module, then add in the placeholder. + if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) { + shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName))); + if (shim) { + shimDeps = lang.isArray(shim) ? shim : shim.deps; + if (config.wrapShim) { + + singleContents = '(function(root) {\n' + + namespaceWithDot + 'define("' + moduleName + '", ' + + (shimDeps && shimDeps.length ? + build.makeJsArrayString(shimDeps) + ', ' : '[], ') + + 'function() {\n' + + ' return (function() {\n' + + singleContents + + // Start with a \n in case last line is a comment + // in the singleContents, like a sourceURL comment. + '\n' + (shim.exportsFn ? shim.exportsFn() : '') + + '\n' + + ' }).apply(root, arguments);\n' + + '});\n' + + '}(this));\n'; + } else { + singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' + + (shimDeps && shimDeps.length ? + build.makeJsArrayString(shimDeps) + ', ' : '') + + (shim.exportsFn ? shim.exportsFn() : 'function(){}') + + ');\n'; + } + } else { + singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n'; + } + } + + //Add line break at end of file, instead of at beginning, + //so source map line numbers stay correct, but still allow + //for some space separation between files in case ASI issues + //for concatenation would cause an error otherwise. + singleContents += '\n'; + + //Add to the source map and to the final contents + fileContents = appendToFileContents(fileContents, singleContents, path, config, module, + sourceMapGenerator); + }); + }; + })).then(function () { + if (onLayerEnds.length) { + onLayerEnds.forEach(function (builder, index) { + var path; + if (typeof module.out === 'string') { + path = module.out; + } else if (typeof module._buildPath === 'string') { + path = module._buildPath; + } + builder.onLayerEnd(function (input) { + fileContents = + appendToFileContents(fileContents, "\n" + addSemiColon(input, config), + 'onLayerEnd' + index + '.js', config, module, sourceMapGenerator); + }, { + name: module.name, + path: path + }); + }); + } + + if (module.create) { + //The ID is for a created layer. Write out + //a module definition for it in case the + //built file is used with enforceDefine + //(#432) + fileContents = + appendToFileContents(fileContents, '\n' + namespaceWithDot + 'define("' + module.name + + '", function(){});\n', 'module-create.js', config, module, + sourceMapGenerator); + } + + //Add a require at the end to kick start module execution, if that + //was desired. Usually this is only specified when using small shim + //loaders like almond. + if (module.insertRequire) { + fileContents = + appendToFileContents(fileContents, '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + + '"]);\n', 'module-insertRequire.js', config, module, + sourceMapGenerator); + } + }); + }).then(function () { + if (config.wrap && config.wrap.__endMap) { + config.wrap.__endMap.forEach(function (wrapFunction) { + fileContents = wrapFunction(fileContents, config, sourceMapGenerator); + }); + } + return { + text: fileContents, + buildText: buildFileContents, + sourceMap: sourceMapGenerator ? + JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') : + undefined + }; + }); + }; + + //Converts an JS array of strings to a string representation. + //Not using JSON.stringify() for Rhino's sake. + build.makeJsArrayString = function (ary) { + return '["' + ary.map(function (item) { + //Escape any double quotes, backslashes + return lang.jsEscape(item); + }).join('","') + '"]'; + }; + + build.toTransport = function (namespace, moduleName, path, contents, layer, options) { + var baseUrl = layer && layer.context.config.baseUrl; + + function onFound(info) { + //Only mark this module as having a name if not a named module, + //or if a named module and the name matches expectations. + if (layer && (info.needsId || info.foundId === moduleName)) { + layer.modulesWithNames[moduleName] = true; + } + } + + //Convert path to be a local one to the baseUrl, useful for + //useSourceUrl. + if (baseUrl) { + path = path.replace(baseUrl, ''); + } + + return transform.toTransport(namespace, moduleName, path, contents, onFound, options); + }; + + return build; +}); + + } + + + /** + * Sets the default baseUrl for requirejs to be directory of top level + * script. + */ + function setBaseUrl(fileName) { + //Use the file name's directory as the baseUrl if available. + dir = fileName.replace(/\\/g, '/'); + if (dir.indexOf('/') !== -1) { + dir = dir.split('/'); + dir.pop(); + dir = dir.join('/'); + //Make sure dir is JS-escaped, since it will be part of a JS string. + exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});"); + } + } + + function createRjsApi() { + //Create a method that will run the optimzer given an object + //config. + requirejs.optimize = function (config, callback, errback) { + if (!loadedOptimizedLib) { + loadLib(); + loadedOptimizedLib = true; + } + + //Create the function that will be called once build modules + //have been loaded. + var runBuild = function (build, logger, quit) { + //Make sure config has a log level, and if not, + //make it "silent" by default. + config.logLevel = config.hasOwnProperty('logLevel') ? + config.logLevel : logger.SILENT; + + //Reset build internals first in case this is part + //of a long-running server process that could have + //exceptioned out in a bad state. It is only defined + //after the first call though. + if (requirejs._buildReset) { + requirejs._buildReset(); + requirejs._cacheReset(); + } + + function done(result) { + //And clean up, in case something else triggers + //a build in another pathway. + if (requirejs._buildReset) { + requirejs._buildReset(); + requirejs._cacheReset(); + } + + // Ensure errors get propagated to the errback + if (result instanceof Error) { + throw result; + } + + return result; + } + + errback = errback || function (err) { + // Using console here since logger may have + // turned off error logging. Since quit is + // called want to be sure a message is printed. + console.log(err); + quit(1); + }; + + build(config).then(done, done).then(callback, errback); + }; + + requirejs({ + context: 'build' + }, ['build', 'logger', 'env!env/quit'], runBuild); + }; + + requirejs.tools = { + useLib: function (contextName, callback) { + if (!callback) { + callback = contextName; + contextName = 'uselib'; + } + + if (!useLibLoaded[contextName]) { + loadLib(); + useLibLoaded[contextName] = true; + } + + var req = requirejs({ + context: contextName + }); + + req(['build'], function () { + callback(req); + }); + } + }; + + requirejs.define = define; + } + + //If in Node, and included via a require('requirejs'), just export and + //THROW IT ON THE GROUND! + if (env === 'node' && reqMain !== module) { + setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.')); + + createRjsApi(); + + module.exports = requirejs; + return; + } else if (env === 'browser') { + //Only option is to use the API. + setBaseUrl(location.href); + createRjsApi(); + return; + } else if ((env === 'rhino' || env === 'xpconnect') && + //User sets up requirejsAsLib variable to indicate it is loaded + //via load() to be used as a library. + typeof requirejsAsLib !== 'undefined' && requirejsAsLib) { + //This script is loaded via rhino's load() method, expose the + //API and get out. + setBaseUrl(fileName); + createRjsApi(); + return; + } + + if (commandOption === 'o') { + //Do the optimizer work. + loadLib(); + + /* + * Create a build.js file that has the build options you want and pass that + * build file to this file to do the build. See example.build.js for more information. + */ + +/*jslint strict: false, nomen: false */ +/*global require: false */ + +require({ + baseUrl: require.s.contexts._.config.baseUrl, + //Use a separate context than the default context so that the + //build can use the default context. + context: 'build', + catchError: { + define: true + } +}, ['env!env/args', 'env!env/quit', 'logger', 'build'], +function (args, quit, logger, build) { + build(args).then(function () {}, function (err) { + logger.error(err); + quit(1); + }); +}); + + + } else if (commandOption === 'v') { + console.log('r.js: ' + version + + ', RequireJS: ' + this.requirejsVars.require.version + + ', UglifyJS: 2.8.29'); + } else if (commandOption === 'convert') { + loadLib(); + + this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'], + function (args, commonJs, print) { + + var srcDir, outDir; + srcDir = args[0]; + outDir = args[1]; + + if (!srcDir || !outDir) { + print('Usage: path/to/commonjs/modules output/dir'); + return; + } + + commonJs.convertDir(args[0], args[1]); + }); + } else { + //Just run an app + + //Load the bundled libraries for use in the app. + if (commandOption === 'lib') { + loadLib(); + } + + setBaseUrl(fileName); + + if (exists(fileName)) { + exec(readFile(fileName), fileName); + } else { + showHelp(); + } + } + +}((typeof console !== 'undefined' ? console : undefined), + (typeof Packages !== 'undefined' || (typeof window === 'undefined' && + typeof Components !== 'undefined' && Components.interfaces) ? + Array.prototype.slice.call(arguments, 0) : []), + (typeof readFile !== 'undefined' ? readFile : undefined))); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/require.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/require.js new file mode 100644 index 0000000000000000000000000000000000000000..857eb5b700075e95bb3660352da06bd2c117ab86 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/require.js @@ -0,0 +1,36 @@ +/* + RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. + Released under MIT license, http://github.com/requirejs/requirejs/LICENSE +*/ +var requirejs,require,define; +(function(ga){function ka(b,c,d,g){return g||""}function K(b){return"[object Function]"===Q.call(b)}function L(b){return"[object Array]"===Q.call(b)}function y(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function X(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));--d);}}function x(b,c){return la.call(b,c)}function e(b,c){return x(b,c)&&b[c]}function D(b,c){for(var d in b)if(x(b,d)&&c(b[d],d))break}function Y(b,c,d,g){c&&D(c,function(c,e){if(d||!x(b,e))!g||"object"!== +typeof c||!c||L(c)||K(c)||c instanceof RegExp?b[e]=c:(b[e]||(b[e]={}),Y(b[e],c,d,g))});return b}function z(b,c){return function(){return c.apply(b,arguments)}}function ha(b){throw b;}function ia(b){if(!b)return b;var c=ga;y(b.split("."),function(b){c=c[b]});return c}function F(b,c,d,g){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=g;d&&(c.originalError=d);return c}function ma(b){function c(a,n,b){var h,k,f,c,d,l,g,r;n=n&&n.split("/");var q=p.map,m=q&&q["*"]; +if(a){a=a.split("/");k=a.length-1;p.nodeIdCompat&&U.test(a[k])&&(a[k]=a[k].replace(U,""));"."===a[0].charAt(0)&&n&&(k=n.slice(0,n.length-1),a=k.concat(a));k=a;for(f=0;f<k.length;f++)c=k[f],"."===c?(k.splice(f,1),--f):".."===c&&0!==f&&(1!==f||".."!==k[2])&&".."!==k[f-1]&&0<f&&(k.splice(f-1,2),f-=2);a=a.join("/")}if(b&&q&&(n||m)){k=a.split("/");f=k.length;a:for(;0<f;--f){d=k.slice(0,f).join("/");if(n)for(c=n.length;0<c;--c)if(b=e(q,n.slice(0,c).join("/")))if(b=e(b,d)){h=b;l=f;break a}!g&&m&&e(m,d)&& +(g=e(m,d),r=f)}!h&&g&&(h=g,l=r);h&&(k.splice(0,l,h),a=k.join("/"))}return(h=e(p.pkgs,a))?h:a}function d(a){E&&y(document.getElementsByTagName("script"),function(n){if(n.getAttribute("data-requiremodule")===a&&n.getAttribute("data-requirecontext")===l.contextName)return n.parentNode.removeChild(n),!0})}function m(a){var n=e(p.paths,a);if(n&&L(n)&&1<n.length)return n.shift(),l.require.undef(a),l.makeRequire(null,{skipMap:!0})([a]),!0}function r(a){var n,b=a?a.indexOf("!"):-1;-1<b&&(n=a.substring(0, +b),a=a.substring(b+1,a.length));return[n,a]}function q(a,n,b,h){var k,f,d=null,g=n?n.name:null,p=a,q=!0,m="";a||(q=!1,a="_@r"+(Q+=1));a=r(a);d=a[0];a=a[1];d&&(d=c(d,g,h),f=e(v,d));a&&(d?m=f&&f.normalize?f.normalize(a,function(a){return c(a,g,h)}):-1===a.indexOf("!")?c(a,g,h):a:(m=c(a,g,h),a=r(m),d=a[0],m=a[1],b=!0,k=l.nameToUrl(m)));b=!d||f||b?"":"_unnormalized"+(T+=1);return{prefix:d,name:m,parentMap:n,unnormalized:!!b,url:k,originalName:p,isDefine:q,id:(d?d+"!"+m:m)+b}}function u(a){var b=a.id, +c=e(t,b);c||(c=t[b]=new l.Module(a));return c}function w(a,b,c){var h=a.id,k=e(t,h);if(!x(v,h)||k&&!k.defineEmitComplete)if(k=u(a),k.error&&"error"===b)c(k.error);else k.on(b,c);else"defined"===b&&c(v[h])}function A(a,b){var c=a.requireModules,h=!1;if(b)b(a);else if(y(c,function(b){if(b=e(t,b))b.error=a,b.events.error&&(h=!0,b.emit("error",a))}),!h)g.onError(a)}function B(){V.length&&(y(V,function(a){var b=a[0];"string"===typeof b&&(l.defQueueMap[b]=!0);G.push(a)}),V=[])}function C(a){delete t[a]; +delete Z[a]}function J(a,b,c){var h=a.map.id;a.error?a.emit("error",a.error):(b[h]=!0,y(a.depMaps,function(h,f){var d=h.id,g=e(t,d);!g||a.depMatched[f]||c[d]||(e(b,d)?(a.defineDep(f,v[d]),a.check()):J(g,b,c))}),c[h]=!0)}function H(){var a,b,c=(a=1E3*p.waitSeconds)&&l.startTime+a<(new Date).getTime(),h=[],k=[],f=!1,g=!0;if(!aa){aa=!0;D(Z,function(a){var l=a.map,e=l.id;if(a.enabled&&(l.isDefine||k.push(a),!a.error))if(!a.inited&&c)m(e)?f=b=!0:(h.push(e),d(e));else if(!a.inited&&a.fetched&&l.isDefine&& +(f=!0,!l.prefix))return g=!1});if(c&&h.length)return a=F("timeout","Load timeout for modules: "+h,null,h),a.contextName=l.contextName,A(a);g&&y(k,function(a){J(a,{},{})});c&&!b||!f||!E&&!ja||ba||(ba=setTimeout(function(){ba=0;H()},50));aa=!1}}function I(a){x(v,a[0])||u(q(a[0],null,!0)).init(a[1],a[2])}function O(a){a=a.currentTarget||a.srcElement;var b=l.onScriptLoad;a.detachEvent&&!ca?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=l.onScriptError;a.detachEvent&&!ca||a.removeEventListener("error", +b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function P(){var a;for(B();G.length;){a=G.shift();if(null===a[0])return A(F("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));I(a)}l.defQueueMap={}}var aa,da,l,R,ba,p={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},t={},Z={},ea={},G=[],v={},W={},fa={},Q=1,T=1;R={require:function(a){return a.require?a.require:a.require=l.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports? +v[a.map.id]=a.exports:a.exports=v[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return e(p.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};da=function(a){this.events=e(ea,a.id)||{};this.map=a;this.shim=e(p.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};da.prototype={init:function(a,b,c,h){h=h||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&& +(c=z(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;this.ignore=h.ignore;h.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,--this.depCount,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;l.startTime=(new Date).getTime();var a=this.map;if(this.shim)l.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],z(this,function(){return a.prefix?this.callPlugin(): +this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;W[a]||(W[a]=!0,l.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var h=this.exports,k=this.factory;if(!this.inited)x(l.defQueueMap,c)||this.fetch();else if(this.error)this.emit("error",this.error);else if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(K(k)){if(this.events.error&&this.map.isDefine||g.onError!== +ha)try{h=l.execCb(c,k,b,h)}catch(d){a=d}else h=l.execCb(c,k,b,h);this.map.isDefine&&void 0===h&&((b=this.module)?h=b.exports:this.usingExports&&(h=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",A(this.error=a)}else h=k;this.exports=h;if(this.map.isDefine&&!this.ignore&&(v[c]=h,g.onResourceLoad)){var f=[];y(this.depMaps,function(a){f.push(a.normalizedMap||a)});g.onResourceLoad(l,this.map,f)}C(c); +this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}},callPlugin:function(){var a=this.map,b=a.id,d=q(a.prefix);this.depMaps.push(d);w(d,"defined",z(this,function(h){var k,f,d=e(fa,this.map.id),M=this.map.name,r=this.map.parentMap?this.map.parentMap.name:null,m=l.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(h.normalize&&(M=h.normalize(M,function(a){return c(a,r,!0)})|| +""),f=q(a.prefix+"!"+M,this.map.parentMap),w(f,"defined",z(this,function(a){this.map.normalizedMap=f;this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),h=e(t,f.id)){this.depMaps.push(f);if(this.events.error)h.on("error",z(this,function(a){this.emit("error",a)}));h.enable()}}else d?(this.map.url=l.nameToUrl(d),this.load()):(k=z(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=z(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];D(t,function(a){0=== +a.map.id.indexOf(b+"_unnormalized")&&C(a.map.id)});A(a)}),k.fromText=z(this,function(h,c){var d=a.name,f=q(d),M=S;c&&(h=c);M&&(S=!1);u(f);x(p.config,b)&&(p.config[d]=p.config[b]);try{g.exec(h)}catch(e){return A(F("fromtexteval","fromText eval for "+b+" failed: "+e,e,[b]))}M&&(S=!0);this.depMaps.push(f);l.completeLoad(d);m([d],k)}),h.load(a.name,m,k,p))}));l.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){Z[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,z(this,function(a, +b){var c,h;if("string"===typeof a){a=q(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=e(R,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;w(a,"defined",z(this,function(a){this.undefed||(this.defineDep(b,a),this.check())}));this.errback?w(a,"error",z(this,this.errback)):this.events.error&&w(a,"error",z(this,function(a){this.emit("error",a)}))}c=a.id;h=t[c];x(R,c)||!h||h.enabled||l.enable(a,this)}));D(this.pluginMaps,z(this,function(a){var b=e(t,a.id); +b&&!b.enabled&&l.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};l={config:p,contextName:b,registry:t,defined:v,urlFetched:W,defQueue:G,defQueueMap:{},Module:da,makeModuleMap:q,nextTick:g.nextTick,onError:A,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");if("string"===typeof a.urlArgs){var b= +a.urlArgs;a.urlArgs=function(a,c){return(-1===c.indexOf("?")?"?":"&")+b}}var c=p.shim,h={paths:!0,bundles:!0,config:!0,map:!0};D(a,function(a,b){h[b]?(p[b]||(p[b]={}),Y(p[b],a,!0,!0)):p[b]=a});a.bundles&&D(a.bundles,function(a,b){y(a,function(a){a!==b&&(fa[a]=b)})});a.shim&&(D(a.shim,function(a,b){L(a)&&(a={deps:a});!a.exports&&!a.init||a.exportsFn||(a.exportsFn=l.makeShimExports(a));c[b]=a}),p.shim=c);a.packages&&y(a.packages,function(a){var b;a="string"===typeof a?{name:a}:a;b=a.name;a.location&& +(p.paths[b]=a.location);p.pkgs[b]=a.name+"/"+(a.main||"main").replace(na,"").replace(U,"")});D(t,function(a,b){a.inited||a.map.unnormalized||(a.map=q(b,null,!0))});(a.deps||a.callback)&&l.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ga,arguments));return b||a.exports&&ia(a.exports)}},makeRequire:function(a,n){function m(c,d,f){var e,r;n.enableBuildCallback&&d&&K(d)&&(d.__requireJsBuild=!0);if("string"===typeof c){if(K(d))return A(F("requireargs", +"Invalid require call"),f);if(a&&x(R,c))return R[c](t[a.id]);if(g.get)return g.get(l,c,a,m);e=q(c,a,!1,!0);e=e.id;return x(v,e)?v[e]:A(F("notloaded",'Module name "'+e+'" has not been loaded yet for context: '+b+(a?"":". Use require([])")))}P();l.nextTick(function(){P();r=u(q(null,a));r.skipMap=n.skipMap;r.init(c,d,f,{enabled:!0});H()});return m}n=n||{};Y(m,{isBrowser:E,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];-1!==f&&("."!==g&&".."!==g||1<f)&&(d=b.substring(f,b.length),b=b.substring(0, +f));return l.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return x(v,q(b,a,!1,!0).id)},specified:function(b){b=q(b,a,!1,!0).id;return x(v,b)||x(t,b)}});a||(m.undef=function(b){B();var c=q(b,a,!0),f=e(t,b);f.undefed=!0;d(b);delete v[b];delete W[c.url];delete ea[b];X(G,function(a,c){a[0]===b&&G.splice(c,1)});delete l.defQueueMap[b];f&&(f.events.defined&&(ea[b]=f.events),C(b))});return m},enable:function(a){e(t,a.id)&&u(a).enable()},completeLoad:function(a){var b,c,d=e(p.shim,a)||{},g=d.exports; +for(B();G.length;){c=G.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);I(c)}l.defQueueMap={};c=e(t,a);if(!b&&!x(v,a)&&c&&!c.inited)if(!p.enforceDefine||g&&ia(g))I([a,d.deps||[],d.exportsFn]);else return m(a)?void 0:A(F("nodefine","No define call for "+a,null,[a]));H()},nameToUrl:function(a,b,c){var d,k,f,m;(d=e(p.pkgs,a))&&(a=d);if(d=e(fa,a))return l.nameToUrl(d,b,c);if(g.jsExtRegExp.test(a))d=a+(b||"");else{d=p.paths;k=a.split("/");for(f=k.length;0<f;--f)if(m=k.slice(0,f).join("/"), +m=e(d,m)){L(m)&&(m=m[0]);k.splice(0,f,m);break}d=k.join("/");d+=b||(/^data\:|^blob\:|\?/.test(d)||c?"":".js");d=("/"===d.charAt(0)||d.match(/^[\w\+\.\-]+:/)?"":p.baseUrl)+d}return p.urlArgs&&!/^blob\:/.test(d)?d+p.urlArgs(a,d):d},load:function(a,b){g.load(l,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||oa.test((a.currentTarget||a.srcElement).readyState))N=null,a=O(a),l.completeLoad(a.id)},onScriptError:function(a){var b=O(a);if(!m(b.id)){var c=[]; +D(t,function(a,d){0!==d.indexOf("_@r")&&y(a.depMaps,function(a){if(a.id===b.id)return c.push(d),!0})});return A(F("scripterror",'Script error for "'+b.id+(c.length?'", needed by: '+c.join(", "):'"'),a,[b.id]))}}};l.require=l.makeRequire();return l}function pa(){if(N&&"interactive"===N.readyState)return N;X(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return N=b});return N}var g,B,C,H,O,I,N,P,u,T,qa=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ra=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, +U=/\.js$/,na=/^\.\//;B=Object.prototype;var Q=B.toString,la=B.hasOwnProperty,E=!("undefined"===typeof window||"undefined"===typeof navigator||!window.document),ja=!E&&"undefined"!==typeof importScripts,oa=E&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,ca="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),J={},w={},V=[],S=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(K(requirejs))return;w=requirejs;requirejs=void 0}"undefined"===typeof require|| +K(require)||(w=require,require=void 0);g=requirejs=function(b,c,d,m){var r,q="_";L(b)||"string"===typeof b||(r=b,L(c)?(b=c,c=d,d=m):b=[]);r&&r.context&&(q=r.context);(m=e(J,q))||(m=J[q]=g.s.newContext(q));r&&m.configure(r);return m.require(b,c,d)};g.config=function(b){return g(b)};g.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=g);g.version="2.2.0";g.jsExtRegExp=/^\/|:|\?|\.js$/;g.isBrowser=E;B=g.s={contexts:J,newContext:ma};g({});y(["toUrl", +"undef","defined","specified"],function(b){g[b]=function(){var c=J._;return c.require[b].apply(c,arguments)}});E&&(C=B.head=document.getElementsByTagName("head")[0],H=document.getElementsByTagName("base")[0])&&(C=B.head=H.parentNode);g.onError=ha;g.createNode=function(b,c,d){c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};g.load=function(b,c,d){var m=b&&b.config|| +{},e;if(E){e=g.createNode(m,c,d);e.setAttribute("data-requirecontext",b.contextName);e.setAttribute("data-requiremodule",c);!e.attachEvent||e.attachEvent.toString&&0>e.attachEvent.toString().indexOf("[native code")||ca?(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)):(S=!0,e.attachEvent("onreadystatechange",b.onScriptLoad));e.src=d;if(m.onNodeCreated)m.onNodeCreated(e,m,c,d);P=e;H?C.insertBefore(e,H):C.appendChild(e);P=null;return e}if(ja)try{setTimeout(function(){}, +0),importScripts(d),b.completeLoad(c)}catch(q){b.onError(F("importscripts","importScripts failed for "+c+" at "+d,q,[c]))}};E&&!w.skipDataMain&&X(document.getElementsByTagName("script"),function(b){C||(C=b.parentNode);if(O=b.getAttribute("data-main"))return u=O,w.baseUrl||-1!==u.indexOf("!")||(I=u.split("/"),u=I.pop(),T=I.length?I.join("/")+"/":"./",w.baseUrl=T),u=u.replace(U,""),g.jsExtRegExp.test(u)&&(u=O),w.deps=w.deps?w.deps.concat(u):[u],!0});define=function(b,c,d){var e,g;"string"!==typeof b&& +(d=c,c=b,b=null);L(c)||(d=c,c=null);!c&&K(d)&&(c=[],d.length&&(d.toString().replace(qa,ka).replace(ra,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));S&&(e=P||pa())&&(b||(b=e.getAttribute("data-requiremodule")),g=J[e.getAttribute("data-requirecontext")]);g?(g.defQueue.push([b,c,d]),g.defQueueMap[b]=!0):V.push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(w)}})(this); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/udpRepeater.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/udpRepeater.js new file mode 100644 index 0000000000000000000000000000000000000000..1f8aac571cd0856e75fcc240f93373267e1527ed --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/scripts/udpRepeater.js @@ -0,0 +1,32 @@ +//set UDP listener +var PORT = 1415; +var HOST = 'localhost'; + +var dgram = require('dgram'); +var server = dgram.createSocket('udp4'); + +//set up WebSocket repeater +const WebSocket = require('ws'); + +const websocket = new WebSocket('ws://track.movesinstitute.org:80'); + +websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; +websocket.onclose = function(evt){console.log("websocket close", evt);}; +websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + + +//turn on udp listener +server.on('listening', function () { + var address = server.address(); + console.log('UDP Server listening on ' + address.address + ":" + address.port); +}); +//when a message is recieved, echo it to the websocket +server.on('message', function (message, remote) { + console.log(remote.address + ':' + remote.port +' - ' + message); + websocket.send(message); + +}); + +server.bind(PORT, HOST); + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tank.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tank.png new file mode 100644 index 0000000000000000000000000000000000000000..460254529fe8218f7fbafd7166f11513fcfdb11e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tank.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tankBig.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tankBig.png new file mode 100644 index 0000000000000000000000000000000000000000..0c57c57a68d057bcdf277f23515d88b7c8f6bcd9 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project/tankBig.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/constructive.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/constructive.html new file mode 100644 index 0000000000000000000000000000000000000000..bbb010706b4d816bbbf849a22d2a721df8be434e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/constructive.html @@ -0,0 +1,64 @@ + +<html> + <head> + <title>Constructive Entity DIS Placement</title> + <meta charset="UTF-8"> + <meta name="viewport" content="width=device-width, initial-scale=1.0"> + <script type="text/javascript" src="scripts/dis.js"></script> + <script data-main="scripts/main" src="scripts/require.js"></script> + </head> + <body onLoad="initialize()"> + + <div> + <h2>Constructive Simulation DIS Entity</H2><p> + + This web page sends Entity State PDUs with the values below. + Fill out the form, and click "Submit." The page will send ESDPUs + with those values to the web server over a websocket, and the server + will transmit them on the local network.<p> + + The Javascript in the web page will send the ESPDUs with the frequency + indicated (in milliseconds). + + </div> + <div id="data"> + + <form id="EspduForm" action="form_action.asp"> + <b>Entity Type Information; Russian T-72 by Default</b><br> + Kind: <input type="text" name="entitykind" id="entitykind" value="1"><br> + Domain: <input type="text" name="domain" id="domain" value="1"><br> + Country <input type="text" name="country" id="country" value="222"><br> + Category<input type="text" name="category" id="category" value="1"><br> + Subcategory<input type="text" name="subcategory" id="subcategory" value="2"><br> + Specific<input type="text" name="specific" id="specific" value="1"><br> + Extra<input type="text" name="extra" id="extra" value="1"><br><br> + + <b>Entity ID site and application</b><br> + Site<input type="text" name="site" id="site" value="48"><br> + Application<input type="text" name="application" id="application" value="23"><br> + <br> + <b>Location</b></br> + Latitude (Decimal degrees):<input type="text" name="latitude" id="latitude" value="36.595"><br> + Longitude<input type="text" name="longitude" id="longitude" value="-121.877"><br> + Altitude (meters)<input type="text" name="altitude" id="altitude" value="10"><br> + +28.425 + <br> + <b>Marking</b> + Marking<input type="text" name="marking" id="marking" value="MyEntity"><br> + <br> + + <br> + <b>Send Frequency </b><br> + Send Frequency (ms)<input type="text" name="sendfrequency" id="sendfrequency" value="5000"><br> + + <input type="button" name="submit" value="Start Sending PDUs" onClick="constructiveSend(this.form)" > +</form> + </div> + + + + <SCRIPT type="text/javascript" src ="scripts/main.js"></SCRIPT> + + </body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/dis.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/dis.js new file mode 100644 index 0000000000000000000000000000000000000000..83d0e716f4d5e1ab8ff391d6d4a73589abd2474e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/dis.js @@ -0,0 +1,13979 @@ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.CoordinateConversion = function() + { + + this.RADIANS_TO_DEGREES = 180.0/Math.PI; + this.DEGREES_TO_RADIANS = Math.PI/180.0; + + this.a = 6378137.0; //semi major axis (WGS 84) + this.b = 6356752.3142; //semi minor axis (WGS 84) + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.CoordinateConversion.prototype.convertDisToLatLongInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared; //second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + var a = 6378137.0; // shorter variable names + var b = 6356752.3142; + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a * a) / Math.sqrt(((a * a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var result = {latitude:answer[0] * this.RADIANS_TO_DEGREES, longitude:answer[1] * this.RADIANS_TO_DEGREES, altitude:answer[2]}; + return result; + + }; + + /** + * Converts lat long and geodetic height (elevation) into DIS XYZ + * This algorithm also uses the WGS84 ellipsoid, though you can change the values + * of a and b for a different ellipsoid. Adapted from Military Handbook 600008 + * @param latLonAlt {lat: lon: alt:} in degrees and meters + * @return {x: y: z:} in meters + */ + dis.CoordinateConversion.prototype.getXYZfromLatLonAltDegrees = function(latLonAlt) + { + var latitudeRadians = latLonAlt.lat * this.DEGREES_TO_RADIANS; + var longtitudeRadians = latLonAlt.lon * this.DEGREES_TO_RADIANS; + + var cosLat = Math.cos(latitudeRadians); + var sinLat = Math.sin(latitudeRadians); + + + var rSubN = (this.a * this.a) / Math.sqrt(((this.a * this.a) * (cosLat * cosLat) + ((this.b * this.b) * (sinLat*sinLat)))); + + var X = (rSubN + latLonAlt.alt) * cosLat * Math.cos(longtitudeRadians); + var Y = (rSubN + latLonAlt.alt) * cosLat * Math.sin(longtitudeRadians); + var Z = ((((this.b * this.b) / (this.a * this.a)) * rSubN) + latLonAlt.alt) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + }; + + exports.CoordinateConversion = dis.CoordinateConversion; +/** + * Obsolete--the code generation now includes methods for accessing bit + * fields such as this. Remains only for backward compatiblity, and I doubt + * anyone is using it. + * + * Some code to extract the entity apperance bit fields.<p> + * + * The entityAppearance field in the espdu is a 32 bit integer. To save + * space, several different fields are contained within it. + * Specifically: + * + * Name bit position Purpose + * ---- ------------ -------- + * Paint 0 0 = uniform color, 1=camo + * Mobility 1 0 = no mobility kill, 1 = mobility kill + * Fire Power 2 0 = no firepower kill, 1 = firepower kill + * Damage 3-4 0=no damange, 1=slight, 2=moderate, 3=destroyed + * Smoke 5-6 0=not smoking, 1=smoke plume, 2=emitting engine smoke, 3=engine smoke + smoke plume + * Trailing effects 7-8 dust cloud, 0=none, 1=small, 2=medium, 3=large + * hatch 9-11 0=NA, 1=hatch closed, 2=popped, 3=popped + person visible, 4=open, 5=open and visible + * head lights 12 0=off, 1=on + * tail light 13 0=off, 1=on + * brake lights 14 0=off, 1=on + * flaming 15 0=none, 1=flames present + * launcher 16 0=not raised, 1=raised + * camo type 17-18 0=desert, 1=winter, 2=forest + * concealed 19 0=not concealed, 1=prepared concealed position (netting, etc) + * frozen status 20 0=not frozen, 1=frozen (in simulation terms) + * power plant 22 0=power plant off 1=on + * state 23 0=active, 1=deactivated + * tent 24 0=not extended 1=extended + * ramp 25 0=not extended, 1=extended + * blackout lights 26 0=off, 1=on + * blackout brake 27 0=off, 1=on + * spot lights 28 0=off, 1=on + * interior lights 29 0=off, 1=on + * unused 30-31 + * + * Typical use: + * + * var entityAppearance = new DisAppearance(espdu.entityAppearance); + * var damage = entityAppearance.getBitfield(3, 4); + * + * This returns the "damage" bitfield in bits 3-4. + * + * var mobility = entityAppearance.getBitfield(1, 1); + * + * Returns the mobility field, 0 = no mobo kill, 1 = mobility kill + * + * @author DMcG + **/ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor. Takes the integer value extracted from the DIS Entity State Field appearance + * + * @param {type} integerValue the entity appearance from the espdu + * @returns {undefined} + */ +dis.DisAppearance = function(integerValue) +{ + this.entityAppearance = integerValue; +} + +/** + * Test code for creating the correct bitmask + * @returns {undefined} + */ +dis.DisAppearance.prototype.getTestMask = function() +{ + mask = 0; + for(var idx = 0; idx < 7; idx++) + { + mask = mask + this.bit_set(mask, idx); + } + + return mask; +}; + +/** + * + * @param {integer} startPosition + * @param {integer} finishPosition + * @returns {integer} + */ +dis.DisAppearance.prototype.getBitField = function(startPosition, finishPosition) +{ + // do some sanity checks + if(startPosition < 0 || startPosition > 31 || finishPosition < 0 || finishPosition > 31 || startPosition > finishPosition) + { + console.log("invalid start or finish for bitfield values: ", startPosition, " ", finishPosition); + return 0; + } + + // Develop the mask. Addition is equivalent to setting multiple bits. + var mask = 0; + for(var idx = startPosition; idx <= finishPosition; idx++) + { + mask = mask + this.bit_set(0, idx); + } + + // do the bitmask + var maskedValue = this.entityAppearance & mask; + // Shift bits to get the normalized value + var fieldValue = maskedValue >>> startPosition; + + return fieldValue; +}; + +/** Set the "bit" position in a number to 1 + * + * @param {integer} num the number whose bit we are setting. Typically zero. + * @param {integer} bit which bit to set + * @return {integer} the number passed in, with the "bit"th bit flipped on. + **/ +dis.DisAppearance.prototype.bit_set = function(num, bit) +{ + return num | 1<<bit; +} + +exports.DisAppearance = dis.DisAppearance; + +//var BigInteger = require('BigInteger'); + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.InputStream = function(binaryData) +{ + this.dataView = new DataView(binaryData, 0); // data, byte offset + this.currentPosition = 0; // ptr to "current" position in array + + dis.InputStream.prototype.readUByte = function() + { + var data = this.dataView.getUint8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readByte = function() + { + var data = this.dataView.getInt8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readUShort = function() + { + var data = this.dataView.getUint16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readShort = function() + { + var data = this.dataView.getInt16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readUInt = function() + { + var data = this.dataView.getUint32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readInt = function() + { + var data = this.dataView.getInt32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + /** Read a long integer. Assumes big endian format. Uses the BigInteger package. */ + dis.InputStream.prototype.readLongInt = function() + { + var data1 = this.dataView.getInt32(this.currentPosition); + var data2 = this.dataView.getInt32(this.currentPosition + 4); + + this.currentPosition = this.currentPosition + 8; + + }; + + dis.InputStream.prototype.readFloat32 = function() + { + var data = this.dataView.getFloat32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readFloat64 = function() + { + var data = this.dataView.getFloat64(this.currentPosition); + this.currentPosition = this.currentPosition + 8; + return data; + }; + + dis.InputStream.prototype.readLong = function() + { + console.log("Problem in dis.InputStream. Javascript cannot natively handle 64 bit ints"); + console.log("Returning 0 from read, which is almost certainly wrong"); + this.currentPosition = this.currentPosition + 8; + return 0; + }; +}; + +exports.InputStream = dis.InputStream; +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * @param binaryDataBuffer ArrayBuffer +*/ +dis.OutputStream = function(binaryDataBuffer) +{ + this.binaryData = binaryDataBuffer; + this.dataView = new DataView(this.binaryData); // data, byte offset + this.currentPosition = 0; // ptr to current position in array + + /** + * Returns a byte array trimmed to the maximum number of bytes written + * to the stream. Eg, if we initialize with a 500 byte bufer, and we + * only write 10 bytes to the output stream, this will return the first + * ten bytes of the array. + * + * @returns {ArrayBuffer} Only the data written + */ + dis.OutputStream.prototype.toByteArray = function() + { + var trimmedData = this.binaryData.slice(0, this.currentPosition); + return trimmedData; + }; + + + dis.OutputStream.prototype.writeUByte = function(userData) + { + this.dataView.setUint8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeByte = function(userData) + { + this.dataView.setInt8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeUShort = function(userData) + { + this.dataView.setUint16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeShort = function(userData) + { + this.dataView.setInt16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeUInt = function(userData) + { + this.dataView.setUint32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeInt = function(userData) + { + this.dataView.setInt32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat32 = function(userData) + { + this.dataView.setFloat32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat64 = function(userData) + { + this.dataView.setFloat64(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 8; + }; + + dis.OutputStream.prototype.writeLong = function(userData) + { + console.log("Problem in dis.outputStream. Javascript cannot natively handle 64 bit ints"); + console.log("writing 0, which is almost certainly wrong"); + this.dataView.setInt32(this.currentPosition, 0); + this.dataView.setInt32(this.currentPosition + 4, 0); + this.currentPosition = this.currentPosition + 8; + }; +}; + +exports.OutputStream = dis.OutputStream; + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + + /** + * The PDU factory is responsible for decoding binary data and turning + * it into the appropriate type of PDU. + * + * The websocket will typically send the web page a IEEE 1278.1 binary + * array of data. It could be any one of dozens of PDUs. The start of + * all PDUs is the same--they have the same header. One of the fields in + * the header is the PduType, an 8 bit integer with a unqiue value for + * each type of PDU. We have to peak at that value, decide what type + * of PDU to create of the binary we have received, and then decode it. + * + * * @DMcG + */ + + dis.PduFactory = function() + { + + }; + + /** + * decode incoming binary data and + * return the correct type of PDU. + * + * @param {type} data the IEEE 1278.1 binary data + * @returns {Pdu} Returns an instance of some PDU, be it espdu, fire, detonation, etc. Exception if PduType not known. + */ + dis.PduFactory.prototype.createPdu = function(data) + { + var asUint8Array = new Uint8Array(data); + var pduType = asUint8Array[2]; + var inputStream = new dis.InputStream(data); + var newPdu = null; + + //try + //{ + switch(pduType) + { + case 1: // entity state PDU + newPdu = new dis.EntityStatePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 2: // Fire + newPdu = new dis.FirePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 3: // detonation + newPdu = new dis.DetonationPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 4: // Collision + newPdu = new dis.CollisionPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 11: // Create entity + newPdu = new dis.CreateEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 12: // Remove entity + newPdu = new dis.RemoveEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 20: // data + newPdu = new dis.DataPdu(); + newPdu.initFromBinary(inputStream); + break; + + default: + throw "PduType: " + pduType + " Unrecognized PDUType. Add PDU in dis.PduFactory."; + } + //} + // This also picks up any errors decoding what we though was a "normal" PDU + //catch(error) + //{ + // newPdu = null; + //} + + return newPdu; + }; + + dis.PduFactory.prototype.getPdusFromBundle = function(data) + { + } + + +exports.PduFactory = dis.PduFactory; +/** + * Sets up a local tangent place (ENU) coordinate system at a given location + * and altitude, and handles conversions between geodetic, ECEF, and local + * tangent plane coordinate systems. + * + * For reference see "Conversion of Geodetic coordinates to the Local + * Tangent Plane", version 2.01, + * http://www.psas.pdx.edu/CoordinateSystem/Latitude_to_LocalTangent.pdf + * + * and "Geodetic Systems", + * http://wiki.gis.com/wiki/index.php/Geodetic_system#From_geodetic_coordinates_to_local_ENU_coordinates + * + * There's also a bunch of ancient code from older versions that someone, somewhere, + * lifted from a military handbook, originally written in C, translated to Java, + * and now translated to Javascript. + * + * Terminology: + * + * ECEF: earth centered, earth fixed coordinate system, same as DIS. Cartesian, + * origin at center of the earth, z through north pole, x out the equator and + * prime meridian, y out equator and 90 deg east. This coordinate system rotates + * with the earth, ie the x axis always points out the prime meridian and equator + * even as the earth rotates. + * + * Geodetic: latitude, longitude, altitude. + * + * WGS84: Shape of the earth, an ellipsoid roughly, with a and b the semimajor and semiminor axes + * + * ENU: East, North, Up: local coordinate system with a given geodetic origin. Tangent + * plane to the earth. + * + * All Errors mine + * + * @DMcG + * + * @param {float} lat latitude in degrees of the origin of the local tangent plane coordinate system + * @param {float} lon longitude, in degrees, of origin + * @param {float} alt altitude, in meters, of the origin of the local tangent plane coordinate system + */ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor, creates an object that can do coordinate systems conversions. + * Takes a geodetic point that is the origin of a tangent plane to the surface + * of the earth. This is useful for doing local simulation work. The local + * coordinate system has postive x east, positive y north, and positive Z up, + * aka an ENU coordinate system. Methods for converting from that coordinate system + * to the DIS (ECEF) coordinate system or geotetic coordinate systems are provided. + * + * @param {type} lat latitude, in degrees, of where the local tangent plane is located + * @param {type} lon longitude, in degrees, of the origin of the local tangent plane + * @param {type} alt altitude, in meters, of the origin of the local tangent plane + * @returns {RangeCoordinates} An object that can do coordinate system conversions + */ +dis.RangeCoordinates = function(lat, lon, alt) +{ + this.RADIANS_PER_DEGREE = 2 * Math.PI / 360.0; + this.DEGREES_PER_RADIAN = 360.0 / (2* Math.PI); + + /** WGS84 semimajor axis (constant) */ + this.a = 6378137.0; + + /** WGS84 semiminor axis (constant) */ + this.b = 6356752.3142; + + /** Ellipsoidal Flatness (constant) */ + this.f = (this.a - this.b) / this.a; // Should be 3.3528107 X 10^-3 + + /** Eccentricity (constant) */ + this.e = Math.sqrt(this.f * (2 - this.f)); // Should be 8.1819191 X 10^-2 + + // The origin of the local, East-North-Up (ENU) coordinate system, in lat/lon degrees and meters. + this.ENUOrigin = {}; + this.ENUOrigin.latitude = lat; + this.ENUOrigin.longitude = lon; + this.ENUOrigin.altitude = alt; + + // Find the origin of the ENU in earth-centered, earth-fixed ECEF aka DIS coordinates + this.ENUOriginInECEF = {}; + this.ENUOriginInECEF = this.latLonAltDegreesToECEF(lat, lon, alt); +}; + + /** Determines N, the distance from a normal plane at the given + * latitude to the Z-axis running through the center of the earth. + * This is NOT the same as the distance to the center of the earth. + * + * @param {float} lambda the latitude, in radians. + * @returns {float} distance in meters from the latitude to the axis of the earth + */ + dis.RangeCoordinates.prototype.N = function(lambda) + { + //N(lambda) = a / sqrt( 1 - e^2 * sin^2(lambda) ) + var val = this.a / Math.sqrt(1- ( Math.pow(this.e, 2) * Math.pow( Math.sin(lambda), 2) ) ); + return val; + }; + + /** + * Converts a latitude, longitude, and altitude object to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {latitude:longitude:altitude:} latLonAlt The lat/lon/alt, in degrees and meters + * @returns {x, y, z} rectilienar coordinates in ECEF, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesObjectToECEF = function(latLonAlt) + { + return this.latLonAltDegreesToECEF(latLonAlt.latitude, latLonAlt.longitude, latLonAlt.altitude); + }; + + /** + * Converts a latitude, longitude, and altitude to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {float} latitude (in radians) + * @param {float} longitude (in radians) + * @param {float} altitude (in meters) + * @returns {x, y, z} rectilienar coordinates in ECEF-r, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltRadiansToECEF = function(latitude, longitude, altitude) + { + /* + // altitude corresponds to h in the paper, lambda to latitude, phi to longitude + var x = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.cos(longitude); + var y = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.sin(longitude); + var z = (altitude + (1 - Math.pow(this.e, 2) ) * this.N(latitude)) * Math.sin(longitude); + + var coordinates = {}; + coordinates.x = x; + coordinates.y = y; + coordinates.z = z; + */ + + var cosLat = Math.cos(latitude); + var sinLat = Math.sin(latitude); + + var rSubN = (this.a*this.a) / Math.sqrt(((this.a*this.a) * (cosLat*cosLat) + ((this.b*this.b) * (sinLat*sinLat)))); + + var X = (rSubN + altitude) * cosLat * Math.cos(longitude); + var Y = (rSubN + altitude) * cosLat * Math.sin(longitude); + var Z = ((((this.b*this.b) / (this.a*this.a)) * rSubN) + altitude) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + + /* + * + * @param {type} latitude in degrees + * @param {type} longitude in degrees + * @param {type} altitude in meters + * @returns {x,y,z} coordinates in ECEF, in meters aka DIS global coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesToECEF = function(latitude, longitude, altitude) + { + return this.latLonAltRadiansToECEF(latitude * this.RADIANS_PER_DEGREE, longitude * this.RADIANS_PER_DEGREE, altitude); + }; + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. (This is + * copied from other sources than those listed above. Seems to work, though.) + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.RangeCoordinates.prototype.ECEFObjectToLatLongAltInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + var a = this.a; // semi major axis (WGS 84) + var b = this.b; //semi minor axis (WGS 84) + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared;//second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a*a) / Math.sqrt(((a*a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var ld = answer[0] * this.DEGREES_PER_RADIAN; + var lnd = answer[1] * this.DEGREES_PER_RADIAN; + var result = {latitude:ld, longitude:lnd, altitude:answer[2]}; + return result; + + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {x:y:z:} ecefPosition ecef position (in meters) + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFObjectToENU = function(ecefPosition) + { + return this.ECEFtoENU(ecefPosition.x, ecefPosition.y, ecefPosition.z); + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {float} X the X coordinate of the ECEF position + * @param {float} Y the Y coordinate + * @param {float} Z the Z coordinate + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFtoENU = function(X, Y, Z) + { + // Origin of ENU tangent plane coordinate system in ECEF coordinate system + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var originLonRadians = this.ENUOrigin.longitude * this.RADIANS_PER_DEGREE; + var originLatRadians = this.ENUOrigin.latitude * this.RADIANS_PER_DEGREE; + + e = -(Math.sin(originLonRadians)) * (X-Xr) + Math.cos(originLonRadians) * (Y-Yr); + n = -(Math.sin(originLatRadians)) * Math.cos(originLonRadians) * (X-Xr) - Math.sin(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.cos(originLatRadians) * (Z-Zr); + u = Math.cos(originLatRadians) * Math.cos(originLonRadians) * (X-Xr) + Math.cos(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.sin(originLatRadians) * (Z-Zr); + + // Local coordinate system x, y, z + return {x:e, y:n, z:u}; + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane object to ECEF, aka DIS coordinates. + * + * @param enuPosition {x:y:z:} local coordinate object + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUObjectToECEF = function(enuPosition) + { + return this.ENUtoECEF(enuPosition.x, enuPosition.y, enuPosition.z); + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane point to ECEF, aka DIS coordinates. + * + * @param localX {float} local coordinate system X + * @param localY {float} local coordinate system Y + * @param localZ {float} local coordinate system Z + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUtoECEF = function(localX, localY, localZ) + { + // ENU local coordinate system origin, in ECEF + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var refLong = this.ENUOrigin.longitude; + var refLat = this.ENUOrigin.latitude; + + /** original code this was copied from + + function [X, Y, Z] = enu2xyz(refLat, refLong, refH, e, n, u) + % Convert east, north, up coordinates (labeled e, n, u) to ECEF + % coordinates. The reference point (phi, lambda, h) must be given. All distances are in metres + + [Xr,Yr,Zr] = llh2xyz(refLat,refLong, refH); % location of reference point + + X = -sin(refLong)*e - cos(refLong)*sin(refLat)*n + cos(refLong)*cos(refLat)*u + Xr; + Y = cos(refLong)*e - sin(refLong)*sin(refLat)*n + cos(refLat)*sin(refLong)*u + Yr; + Z = cos(refLat)*n + sin(refLat)*u + Zr; + */ + + X = -(Math.sin(refLong)) * localX - Math.cos(refLong) * Math.sin(refLat) * localY + Math.cos(refLong) * Math.cos(refLat) * localZ + Xr; + Y = Math.cos(refLong) * localX - Math.sin(refLong) * Math.sin(refLat) * localY + Math.cos(refLat) * Math.sin(refLong) * localZ + Yr; + Z = Math.cos(refLat) * localY + Math.sin(refLat) * localZ + Zr; + + return {x:X, y:Y, z:Z}; + }; + +exports.RangeCoordinates = dis.RangeCoordinates;if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * Utility class that converts between strings and the DIS ESPDU marking + * field. The marking field is 12 bytes long, with the first byte being + * the character set used, and the remaining 11 bytes character codes in + * that character set. This is often used for debugging or "billboard" + * displays in 3D; it's intended for humans. The string character values + * are clamped (or filled) to exactly 11 bytes, so "This is a long string" + * will be clamped to "This is a l" (in charachter codes) and "foo" will + * be filled to "foo\0\0\0\0\0\0\0\0".<p> + * + * It is recommended that only ASCII character set (character set = 1) + * be used. + * + * @returns {undefined} + */ +dis.StringConversion = function() +{ +}; + +/** + * Given a string, returns a DIS marking field. The character set is set to + * 1, for ascii. The length is clamped to 11, and zero-filled if the string + * is shorter than 11. + * + * @returns {array} disMarking field, 12 bytes long, character set = 1 (ascii) in 0, zero-filled to 11 character codes + */ +dis.StringConversion.prototype.StringToDisMarking = function(markingString) +{ + var byteMarking = []; + + // character set 1 = ascii + byteMarking.push(1); + + var markingLength = markingString.length; + + // Clamp it to 11 bytes of character data + if(markingLength > 11) + markingLength = 11; + + // If the string is shorter than 11 bytes, we zero-fill the array + var diff = 11 - markingLength; + + for(var idx = 0; idx < markingLength; idx++) + { + byteMarking.push(markingString.charCodeAt(idx)); + } + + for(var idx = markingLength; idx < 11; idx++) + { + byteMarking.push(0); + } + + return byteMarking; +}; + +/** + * Given a DIS marking field, returns a string. Assumes always ascii. + * + * @param {array} disMarking dis marking field, [0] = character set, the rest character codes + * @returns {string} string equivalent of the marking field + */ +dis.StringConversion.prototype.DisMarkingToString = function(disMarking) +{ + var marking = ""; + + for(var idx = 1; idx < disMarking.length; idx++) + { + marking = marking + String.fromCharCode(disMarking[idx]); + } + + return marking; +}; + +// This is a temporary placeholder until full require.js code +// support is present. +if (typeof exports === "undefined") + exports = {}; + +exports.RangeCoordinates = dis.RangeCoordinates; +exports.InputStream = dis.InputStream; +exports.OutputStream = dis.OutputStream; + +/** + * Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 15; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** type of message being acknowledged */ + this.acknowledgeFlag = 0; + + /** Whether or not the receiving entity was able to comply with the request */ + this.responseFlag = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.AcknowledgePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgePdu = dis.AcknowledgePdu; + +// End of AcknowledgePdu class + +/** + * Section 5.3.12.5: Ack receipt of a start-resume, stop-freeze, create-entity or remove enitty (reliable) pdus. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 55; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** ack flags */ + this.acknowledgeFlag = 0; + + /** response flags */ + this.responseFlag = 0; + + /** Request ID */ + this.requestID = 0; + + dis.AcknowledgeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgeReliablePdu = dis.AcknowledgeReliablePdu; + +// End of AcknowledgeReliablePdu class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamData = function() +{ + /** beam data length */ + this.beamDataLength = 0; + + /** beamIDNumber */ + this.beamIDNumber = 0; + + /** padding */ + this.pad2 = 0; + + /** fundamental data parameters */ + this.fundamentalDataParameters = new dis.AcousticBeamFundamentalParameter(); + + dis.AcousticBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUShort(); + this.beamIDNumber = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.fundamentalDataParameters.initFromBinary(inputStream); + }; + + dis.AcousticBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.pad2); + this.fundamentalDataParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamData = dis.AcousticBeamData; + +// End of AcousticBeamData class + +/** + * Used in UaPdu + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamFundamentalParameter = function() +{ + /** parameter index */ + this.activeEmissionParameterIndex = 0; + + /** scan pattern */ + this.scanPattern = 0; + + /** beam center azimuth */ + this.beamCenterAzimuth = 0; + + /** azimuthal beamwidth */ + this.azimuthalBeamwidth = 0; + + /** beam center */ + this.beamCenterDE = 0; + + /** DE beamwidth (vertical beamwidth) */ + this.deBeamwidth = 0; + + dis.AcousticBeamFundamentalParameter.prototype.initFromBinary = function(inputStream) + { + this.activeEmissionParameterIndex = inputStream.readUShort(); + this.scanPattern = inputStream.readUShort(); + this.beamCenterAzimuth = inputStream.readFloat32(); + this.azimuthalBeamwidth = inputStream.readFloat32(); + this.beamCenterDE = inputStream.readFloat32(); + this.deBeamwidth = inputStream.readFloat32(); + }; + + dis.AcousticBeamFundamentalParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.activeEmissionParameterIndex); + outputStream.writeUShort(this.scanPattern); + outputStream.writeFloat32(this.beamCenterAzimuth); + outputStream.writeFloat32(this.azimuthalBeamwidth); + outputStream.writeFloat32(this.beamCenterDE); + outputStream.writeFloat32(this.deBeamwidth); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamFundamentalParameter = dis.AcousticBeamFundamentalParameter; + +// End of AcousticBeamFundamentalParameter class + +/** + * Section 5.2.35. information about a specific UA emmtter + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitter = function() +{ + /** the system for a particular UA emitter, and an enumeration */ + this.acousticName = 0; + + /** The function of the acoustic system */ + this.function = 0; + + /** The UA emitter identification number relative to a specific system */ + this.acousticIdNumber = 0; + + dis.AcousticEmitter.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.acousticIdNumber = inputStream.readUByte(); + }; + + dis.AcousticEmitter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.acousticIdNumber); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitter = dis.AcousticEmitter; + +// End of AcousticEmitter class + +/** + * 5.3.35: Information about a particular UA emitter shall be represented using an Acoustic Emitter System record. This record shall consist of three fields: Acoustic Name, Function, and Acoustic ID Number + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystem = function() +{ + /** This field shall specify the system for a particular UA emitter. */ + this.acousticName = 0; + + /** This field shall describe the function of the acoustic system. */ + this.acousticFunction = 0; + + /** This field shall specify the UA emitter identification number relative to a specific system. This field shall be represented by an 8-bit unsigned integer. This field allows the differentiation of multiple systems on an entity, even if in some instances two or more of the systems may be identical UA emitter types. Numbering of systems shall begin with the value 1. */ + this.acousticID = 0; + + dis.AcousticEmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.acousticFunction = inputStream.readUByte(); + this.acousticID = inputStream.readUByte(); + }; + + dis.AcousticEmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.acousticFunction); + outputStream.writeUByte(this.acousticID); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystem = dis.AcousticEmitterSystem; + +// End of AcousticEmitterSystem class + +/** + * Used in the UA pdu; ties together an emmitter and a location. This requires manual cleanup; the beam data should not be attached to each emitter system. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystemData = function() +{ + /** Length of emitter system data */ + this.emitterSystemDataLength = 0; + + /** Number of beams */ + this.numberOfBeams = 0; + + /** padding */ + this.pad2 = 0; + + /** This field shall specify the system for a particular UA emitter. */ + this.acousticEmitterSystem = new dis.AcousticEmitterSystem(); + + /** Represents the location wrt the entity */ + this.emitterLocation = new dis.Vector3Float(); + + /** For each beam in numberOfBeams, an emitter system. This is not right--the beam records need to be at the end of the PDU, rather than attached to each system. */ + this.beamRecords = new Array(); + + dis.AcousticEmitterSystemData.prototype.initFromBinary = function(inputStream) + { + this.emitterSystemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.acousticEmitterSystem.initFromBinary(inputStream); + this.emitterLocation.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.AcousticBeamData(); + anX.initFromBinary(inputStream); + this.beamRecords.push(anX); + } + + }; + + dis.AcousticEmitterSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.emitterSystemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.pad2); + this.acousticEmitterSystem.encodeToBinary(outputStream); + this.emitterLocation.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamRecords.length; idx++) + { + beamRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystemData = dis.AcousticEmitterSystemData; + +// End of AcousticEmitterSystemData class + +/** + * Section 5.3.6.6. Request from simulation manager to an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 16; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** identifies the action being requested */ + this.actionID = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestPdu = dis.ActionRequestPdu; + +// End of ActionRequestPdu class + +/** + * Section 5.3.12.6: request from a simulation manager to a managed entity to perform a specified action. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 56; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** request ID */ + this.actionID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionRequestReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionRequestReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestReliablePdu = dis.ActionRequestReliablePdu; + +// End of ActionRequestReliablePdu class + +/** + * Section 5.3.6.7. response to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 17; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** Status of response */ + this.requestStatus = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requestStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.requestStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponsePdu = dis.ActionResponsePdu; + +// End of ActionResponsePdu class + +/** + * Section 5.3.12.7: Response from an entity to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponseReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 57; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** status of response */ + this.responseStatus = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionResponseReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.responseStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionResponseReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.responseStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponseReliablePdu = dis.ActionResponseReliablePdu; + +// End of ActionResponseReliablePdu class + +/** + * Section 5.2.36. Each agregate in a given simulation app is given an aggregate identifier number unique for all other aggregates in that app and in that exercise. The id is valid for the duration of the the exercise. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the aggregate ID */ + this.aggregateID = 0; + + dis.AggregateID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.aggregateID = inputStream.readUShort(); + }; + + dis.AggregateID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.aggregateID); + }; +}; // end of class + + // node.js module support +exports.AggregateID = dis.AggregateID; + +// End of AggregateID class + +/** + * Section 5.2.37. Specifies the character set used inthe first byte, followed by up to 31 characters of text data. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateMarking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.AggregateMarking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 31; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.AggregateMarking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 31; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.AggregateMarking = dis.AggregateMarking; + +// End of AggregateMarking class + +/** + * Section 5.3.9.1 informationa bout aggregating entities anc communicating information about the aggregated entities. requires manual intervention to fix the padding between entityID lists and silent aggregate sysem lists--this padding is dependent on how many entityIDs there are, and needs to be on a 32 bit word boundary. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 33; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.aggregateID = new dis.EntityID(); + + /** force ID */ + this.forceID = 0; + + /** state of aggregate */ + this.aggregateState = 0; + + /** entity type of the aggregated entities */ + this.aggregateType = new dis.EntityType(); + + /** formation of aggregated entities */ + this.formation = 0; + + /** marking for aggregate; first char is charset type, rest is char data */ + this.aggregateMarking = new dis.AggregateMarking(); + + /** dimensions of bounding box for the aggregated entities, origin at the center of mass */ + this.dimensions = new dis.Vector3Float(); + + /** orientation of the bounding box */ + this.orientation = new dis.Orientation(); + + /** center of mass of the aggregation */ + this.centerOfMass = new dis.Vector3Double(); + + /** velocity of aggregation */ + this.velocity = new dis.Vector3Float(); + + /** number of aggregates */ + this.numberOfDisAggregates = 0; + + /** number of entities */ + this.numberOfDisEntities = 0; + + /** number of silent aggregate types */ + this.numberOfSilentAggregateTypes = 0; + + /** number of silent entity types */ + this.numberOfSilentEntityTypes = 0; + + /** aggregates list */ + this.aggregateIDList = new Array(); + + /** entity ID list */ + this.entityIDList = new Array(); + + /** ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed */ + this.pad2 = 0; + + /** silent entity types */ + this.silentAggregateSystemList = new Array(); + + /** silent entity types */ + this.silentEntitySystemList = new Array(); + + /** number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variableDatums */ + this.variableDatumList = new Array(); + + dis.AggregateStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.aggregateID.initFromBinary(inputStream); + this.forceID = inputStream.readUByte(); + this.aggregateState = inputStream.readUByte(); + this.aggregateType.initFromBinary(inputStream); + this.formation = inputStream.readUInt(); + this.aggregateMarking.initFromBinary(inputStream); + this.dimensions.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.centerOfMass.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.numberOfDisAggregates = inputStream.readUShort(); + this.numberOfDisEntities = inputStream.readUShort(); + this.numberOfSilentAggregateTypes = inputStream.readUShort(); + this.numberOfSilentEntityTypes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfDisAggregates; idx++) + { + var anX = new dis.AggregateID(); + anX.initFromBinary(inputStream); + this.aggregateIDList.push(anX); + } + + for(var idx = 0; idx < this.numberOfDisEntities; idx++) + { + var anX = new dis.EntityID(); + anX.initFromBinary(inputStream); + this.entityIDList.push(anX); + } + + this.pad2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfSilentAggregateTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentAggregateSystemList.push(anX); + } + + for(var idx = 0; idx < this.numberOfSilentEntityTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentEntitySystemList.push(anX); + } + + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumList.push(anX); + } + + }; + + dis.AggregateStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.aggregateID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.aggregateState); + this.aggregateType.encodeToBinary(outputStream); + outputStream.writeUInt(this.formation); + this.aggregateMarking.encodeToBinary(outputStream); + this.dimensions.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + this.centerOfMass.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfDisAggregates); + outputStream.writeUShort(this.numberOfDisEntities); + outputStream.writeUShort(this.numberOfSilentAggregateTypes); + outputStream.writeUShort(this.numberOfSilentEntityTypes); + for(var idx = 0; idx < this.aggregateIDList.length; idx++) + { + aggregateIDList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.entityIDList.length; idx++) + { + entityIDList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad2); + for(var idx = 0; idx < this.silentAggregateSystemList.length; idx++) + { + silentAggregateSystemList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.silentEntitySystemList.length; idx++) + { + silentEntitySystemList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.variableDatumList.length; idx++) + { + variableDatumList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AggregateStatePdu = dis.AggregateStatePdu; + +// End of AggregateStatePdu class + +/** + * Section 5.2.38. Identifies the type of aggregate including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateType = function() +{ + /** Kind of entity */ + this.aggregateKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field, sql has a reserved word for specific */ + this.specificInfo = 0; + + this.extra = 0; + + dis.AggregateType.prototype.initFromBinary = function(inputStream) + { + this.aggregateKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specificInfo = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.AggregateType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.aggregateKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specificInfo); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.AggregateType = dis.AggregateType; + +// End of AggregateType class + +/** + * 5.2.2: angular velocity measured in radians per second out each of the entity's own coordinate axes. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AngularVelocityVector = function() +{ + /** velocity about the x axis */ + this.x = 0; + + /** velocity about the y axis */ + this.y = 0; + + /** velocity about the zaxis */ + this.z = 0; + + dis.AngularVelocityVector.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.AngularVelocityVector.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.AngularVelocityVector = dis.AngularVelocityVector; + +// End of AngularVelocityVector class + +/** + * 5.2.3: location of the radiating portion of the antenna, specified in world coordinates and entity coordinates. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AntennaLocation = function() +{ + /** Location of the radiating portion of the antenna in world coordinates */ + this.antennaLocation = new dis.Vector3Double(); + + /** Location of the radiating portion of the antenna in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + dis.AntennaLocation.prototype.initFromBinary = function(inputStream) + { + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + }; + + dis.AntennaLocation.prototype.encodeToBinary = function(outputStream) + { + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AntennaLocation = dis.AntennaLocation; + +// End of AntennaLocation class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ApaData = function() +{ + /** Index of APA parameter */ + this.parameterIndex = 0; + + /** Index of APA parameter */ + this.parameterValue = 0; + + dis.ApaData.prototype.initFromBinary = function(inputStream) + { + this.parameterIndex = inputStream.readUShort(); + this.parameterValue = inputStream.readShort(); + }; + + dis.ApaData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.parameterIndex); + outputStream.writeShort(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ApaData = dis.ApaData; + +// End of ApaData class + +/** + * Section 5.3.11.5: Information about the addition/modification of an oobject that is geometrically achored to the terrain with a set of three or more points that come to a closure. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArealObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 45; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications enumeration */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.EntityType(); + + /** Object appearance */ + this.objectAppearance = new dis.SixByteChunk(); + + /** Number of points */ + this.numberOfPoints = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** location of object */ + this.objectLocation = new Array(); + + dis.ArealObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectAppearance.initFromBinary(inputStream); + this.numberOfPoints = inputStream.readUShort(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPoints; idx++) + { + var anX = new dis.Vector3Double(); + anX.initFromBinary(inputStream); + this.objectLocation.push(anX); + } + + }; + + dis.ArealObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectAppearance.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfPoints); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + for(var idx = 0; idx < this.objectLocation.length; idx++) + { + objectLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ArealObjectStatePdu = dis.ArealObjectStatePdu; + +// End of ArealObjectStatePdu class + +/** + * Section 5.2.5. Articulation parameters for movable parts and attached parts of an entity. Specifes wether or not a change has occured, the part identifcation of the articulated part to which it is attached, and the type and value of each parameter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArticulationParameter = function() +{ + this.parameterTypeDesignator = 0; + + this.changeIndicator = 0; + + this.partAttachedTo = 0; + + this.parameterType = 0; + + this.parameterValue = 0; + + dis.ArticulationParameter.prototype.initFromBinary = function(inputStream) + { + this.parameterTypeDesignator = inputStream.readUByte(); + this.changeIndicator = inputStream.readUByte(); + this.partAttachedTo = inputStream.readUShort(); + this.parameterType = inputStream.readInt(); + this.parameterValue = inputStream.readFloat64(); + }; + + dis.ArticulationParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.parameterTypeDesignator); + outputStream.writeUByte(this.changeIndicator); + outputStream.writeUShort(this.partAttachedTo); + outputStream.writeInt(this.parameterType); + outputStream.writeFloat64(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ArticulationParameter = dis.ArticulationParameter; + +// End of ArticulationParameter class + +/** + * Section 5.2.4.2. Used when the antenna pattern type field has a value of 1. Specifies the direction, patter, and polarization of radiation from an antenna. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamAntennaPattern = function() +{ + /** The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record. */ + this.beamDirection = new dis.Orientation(); + + this.azimuthBeamwidth = 0; + + this.elevationBeamwidth = 0; + + this.referenceSystem = 0; + + this.padding1 = 0; + + this.padding2 = 0; + + /** Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ez = 0; + + /** Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ex = 0; + + /** THe phase angle between Ez and Ex in radians. */ + this.phase = 0; + + dis.BeamAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.beamDirection.initFromBinary(inputStream); + this.azimuthBeamwidth = inputStream.readFloat32(); + this.elevationBeamwidth = inputStream.readFloat32(); + this.referenceSystem = inputStream.readFloat32(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + this.ez = inputStream.readFloat32(); + this.ex = inputStream.readFloat32(); + this.phase = inputStream.readFloat32(); + }; + + dis.BeamAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + this.beamDirection.encodeToBinary(outputStream); + outputStream.writeFloat32(this.azimuthBeamwidth); + outputStream.writeFloat32(this.elevationBeamwidth); + outputStream.writeFloat32(this.referenceSystem); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + outputStream.writeFloat32(this.ez); + outputStream.writeFloat32(this.ex); + outputStream.writeFloat32(this.phase); + }; +}; // end of class + + // node.js module support +exports.BeamAntennaPattern = dis.BeamAntennaPattern; + +// End of BeamAntennaPattern class + +/** + * Section 5.2.39. Specification of the data necessary to describe the scan volume of an emitter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamData = function() +{ + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.BeamData.prototype.initFromBinary = function(inputStream) + { + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.BeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.BeamData = dis.BeamData; + +// End of BeamData class + +/** + * Section 5.2.7. Specifies the type of muntion fired, the type of warhead, the type of fuse, the number of rounds fired, and the rate at which the roudns are fired in rounds per minute. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BurstDescriptor = function() +{ + /** What munition was used in the burst */ + this.munition = new dis.EntityType(); + + /** type of warhead */ + this.warhead = 0; + + /** type of fuse used */ + this.fuse = 0; + + /** how many of the munition were fired */ + this.quantity = 0; + + /** rate at which the munition was fired */ + this.rate = 0; + + dis.BurstDescriptor.prototype.initFromBinary = function(inputStream) + { + this.munition.initFromBinary(inputStream); + this.warhead = inputStream.readUShort(); + this.fuse = inputStream.readUShort(); + this.quantity = inputStream.readUShort(); + this.rate = inputStream.readUShort(); + }; + + dis.BurstDescriptor.prototype.encodeToBinary = function(outputStream) + { + this.munition.encodeToBinary(outputStream); + outputStream.writeUShort(this.warhead); + outputStream.writeUShort(this.fuse); + outputStream.writeUShort(this.quantity); + outputStream.writeUShort(this.rate); + }; +}; // end of class + + // node.js module support +exports.BurstDescriptor = dis.BurstDescriptor; + +// End of BurstDescriptor class + +/** + * Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ClockTime = function() +{ + /** Hours in UTC */ + this.hour = 0; + + /** Time past the hour */ + this.timePastHour = 0; + + dis.ClockTime.prototype.initFromBinary = function(inputStream) + { + this.hour = inputStream.readInt(); + this.timePastHour = inputStream.readUInt(); + }; + + dis.ClockTime.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.hour); + outputStream.writeUInt(this.timePastHour); + }; +}; // end of class + + // node.js module support +exports.ClockTime = dis.ClockTime; + +// End of ClockTime class + +/** + * 5.3.3.3. Information about elastic collisions in a DIS exercise shall be communicated using a Collision-Elastic PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionElasticPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 66; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.collisionEventID = new dis.EventID(); + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.contactVelocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + /** tensor values */ + this.collisionResultXX = 0; + + /** tensor values */ + this.collisionResultXY = 0; + + /** tensor values */ + this.collisionResultXZ = 0; + + /** tensor values */ + this.collisionResultYY = 0; + + /** tensor values */ + this.collisionResultYZ = 0; + + /** tensor values */ + this.collisionResultZZ = 0; + + /** This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates. */ + this.unitSurfaceNormal = new dis.Vector3Float(); + + /** This field shall represent the degree to which energy is conserved in a collision */ + this.coefficientOfRestitution = 0; + + dis.CollisionElasticPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.collisionEventID.initFromBinary(inputStream); + this.pad = inputStream.readShort(); + this.contactVelocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + this.collisionResultXX = inputStream.readFloat32(); + this.collisionResultXY = inputStream.readFloat32(); + this.collisionResultXZ = inputStream.readFloat32(); + this.collisionResultYY = inputStream.readFloat32(); + this.collisionResultYZ = inputStream.readFloat32(); + this.collisionResultZZ = inputStream.readFloat32(); + this.unitSurfaceNormal.initFromBinary(inputStream); + this.coefficientOfRestitution = inputStream.readFloat32(); + }; + + dis.CollisionElasticPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.collisionEventID.encodeToBinary(outputStream); + outputStream.writeShort(this.pad); + this.contactVelocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + outputStream.writeFloat32(this.collisionResultXX); + outputStream.writeFloat32(this.collisionResultXY); + outputStream.writeFloat32(this.collisionResultXZ); + outputStream.writeFloat32(this.collisionResultYY); + outputStream.writeFloat32(this.collisionResultYZ); + outputStream.writeFloat32(this.collisionResultZZ); + this.unitSurfaceNormal.encodeToBinary(outputStream); + outputStream.writeFloat32(this.coefficientOfRestitution); + }; +}; // end of class + + // node.js module support +exports.CollisionElasticPdu = dis.CollisionElasticPdu; + +// End of CollisionElasticPdu class + +/** + * Section 5.3.3.2. Information about a collision. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 4; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** ID of event */ + this.collisionType = 0; + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.velocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + dis.CollisionPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.collisionType = inputStream.readUByte(); + this.pad = inputStream.readByte(); + this.velocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + }; + + dis.CollisionPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.collisionType); + outputStream.writeByte(this.pad); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.CollisionPdu = dis.CollisionPdu; + +// End of CollisionPdu class + +/** + * Section 5.3.6.12. Arbitrary messages can be entered into the data stream via use of this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 22; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.CommentPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.CommentPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentPdu = dis.CommentPdu; + +// End of CommentPdu class + +/** + * Section 5.3.12.12: Arbitrary messages. Only reliable this time. Neds manual intervention to fix padding in variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 62; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.CommentReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.CommentReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentReliablePdu = dis.CommentReliablePdu; + +// End of CommentReliablePdu class + +/** + * Section 5.3.6.1. Create a new entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 11; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.CreateEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityPdu = dis.CreateEntityPdu; + +// End of CreateEntityPdu class + +/** + * Section 5.3.12.1: creation of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 51; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.CreateEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityReliablePdu = dis.CreateEntityReliablePdu; + +// End of CreateEntityReliablePdu class + +/** + * Section 5.3.6.10. Information issued in response to a data query pdu or a set data pdu is communicated using a data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 20; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataPdu = dis.DataPdu; + +// End of DataPdu class + +/** + * Section 5.3.6.8. Request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 18; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** time issues between issues of Data PDUs. Zero means send once only. */ + this.timeInterval = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryPdu = dis.DataQueryPdu; + +// End of DataQueryPdu class + +/** + * Section 5.3.12.8: request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 58; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** time interval between issuing data query PDUs */ + this.timeInterval = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryReliablePdu = dis.DataQueryReliablePdu; + +// End of DataQueryReliablePdu class + +/** + * Section 5.3.12.10: issued in response to a data query R or set dataR pdu. Needs manual intervention to fix padding on variable datums. UNFINSIHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 60; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataReliablePdu = dis.DataReliablePdu; + +// End of DataReliablePdu class + +/** + * represents values used in dead reckoning algorithms + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DeadReckoningParameter = function() +{ + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Linear acceleration of the entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + /** angular velocity of the entity */ + this.entityAngularVelocity = new dis.Vector3Float(); + + dis.DeadReckoningParameter.prototype.initFromBinary = function(inputStream) + { + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.entityLinearAcceleration.initFromBinary(inputStream); + this.entityAngularVelocity.initFromBinary(inputStream); + }; + + dis.DeadReckoningParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + this.entityLinearAcceleration.encodeToBinary(outputStream); + this.entityAngularVelocity.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DeadReckoningParameter = dis.DeadReckoningParameter; + +// End of DeadReckoningParameter class + +/** + * Section 5.3.7.2. Handles designating operations. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DesignatorPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 24; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity designating */ + this.designatingEntityID = new dis.EntityID(); + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.codeName = 0; + + /** ID of the entity being designated */ + this.designatedEntityID = new dis.EntityID(); + + /** This field shall identify the designator code being used by the designating entity */ + this.designatorCode = 0; + + /** This field shall identify the designator output power in watts */ + this.designatorPower = 0; + + /** This field shall identify the designator wavelength in units of microns */ + this.designatorWavelength = 0; + + /** designtor spot wrt the designated entity */ + this.designatorSpotWrtDesignated = new dis.Vector3Float(); + + /** designtor spot wrt the designated entity */ + this.designatorSpotLocation = new dis.Vector3Double(); + + /** Dead reckoning algorithm */ + this.deadReckoningAlgorithm = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** linear accelleration of entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + dis.DesignatorPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.designatingEntityID.initFromBinary(inputStream); + this.codeName = inputStream.readUShort(); + this.designatedEntityID.initFromBinary(inputStream); + this.designatorCode = inputStream.readUShort(); + this.designatorPower = inputStream.readFloat32(); + this.designatorWavelength = inputStream.readFloat32(); + this.designatorSpotWrtDesignated.initFromBinary(inputStream); + this.designatorSpotLocation.initFromBinary(inputStream); + this.deadReckoningAlgorithm = inputStream.readByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readByte(); + this.entityLinearAcceleration.initFromBinary(inputStream); + }; + + dis.DesignatorPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.designatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.codeName); + this.designatedEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.designatorCode); + outputStream.writeFloat32(this.designatorPower); + outputStream.writeFloat32(this.designatorWavelength); + this.designatorSpotWrtDesignated.encodeToBinary(outputStream); + this.designatorSpotLocation.encodeToBinary(outputStream); + outputStream.writeByte(this.deadReckoningAlgorithm); + outputStream.writeUShort(this.padding1); + outputStream.writeByte(this.padding2); + this.entityLinearAcceleration.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DesignatorPdu = dis.DesignatorPdu; + +// End of DesignatorPdu class + +/** + * Section 5.3.4.2. Information about stuff exploding. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DetonationPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 3; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of muntion that was fired */ + this.munitionID = new dis.EntityID(); + + /** ID firing event */ + this.eventID = new dis.EventID(); + + /** ID firing event */ + this.velocity = new dis.Vector3Float(); + + /** where the detonation is, in world coordinates */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munition used */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** location of the detonation or impact in the target entity's coordinate system. This information should be used for damage assessment. */ + this.locationInEntityCoordinates = new dis.Vector3Float(); + + /** result of the explosion */ + this.detonationResult = 0; + + /** How many articulation parameters we have */ + this.numberOfArticulationParameters = 0; + + /** padding */ + this.pad = 0; + + this.articulationParameters = new Array(); + + dis.DetonationPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.locationInEntityCoordinates.initFromBinary(inputStream); + this.detonationResult = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.pad = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.DetonationPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.locationInEntityCoordinates.encodeToBinary(outputStream); + outputStream.writeUByte(this.detonationResult); + outputStream.writeUByte(this.numberOfArticulationParameters); + outputStream.writeShort(this.pad); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DetonationPdu = dis.DetonationPdu; + +// End of DetonationPdu class + +/** + * Section 5.3.7. Electronic Emissions. Abstract superclass for distirubted emissions PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DistributedEmissionsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.DistributedEmissionsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.DistributedEmissionsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.DistributedEmissionsFamilyPdu = dis.DistributedEmissionsFamilyPdu; + +// End of DistributedEmissionsFamilyPdu class + +/** + * 64 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EightByteChunk = function() +{ + /** Eight bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0); + + dis.EightByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 8; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.EightByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 8; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.EightByteChunk = dis.EightByteChunk; + +// End of EightByteChunk class + +/** + * Description of one electronic emission beam + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionBeamData = function() +{ + /** This field shall specify the length of this beams data in 32 bit words */ + this.beamDataLength = 0; + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.beamIDNumber = 0; + + /** This field shall specify a Beam Parameter Index number that shall be used by receiving entities in conjunction with the Emitter Name field to provide a pointer to the stored database parameters required to regenerate the beam. */ + this.beamParameterIndex = 0; + + /** Fundamental parameter data such as frequency range, beam sweep, etc. */ + this.fundamentalParameterData = new dis.FundamentalParameterData(); + + /** beam function of a particular beam */ + this.beamFunction = 0; + + /** Number of track/jam targets */ + this.numberOfTrackJamTargets = 0; + + /** wheher or not the receiving simulation apps can assume all the targets in the scan pattern are being tracked/jammed */ + this.highDensityTrackJam = 0; + + /** padding */ + this.pad4 = 0; + + /** identify jamming techniques used */ + this.jammingModeSequence = 0; + + /** variable length variablelist of track/jam targets */ + this.trackJamTargets = new Array(); + + dis.ElectronicEmissionBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUByte(); + this.beamIDNumber = inputStream.readUByte(); + this.beamParameterIndex = inputStream.readUShort(); + this.fundamentalParameterData.initFromBinary(inputStream); + this.beamFunction = inputStream.readUByte(); + this.numberOfTrackJamTargets = inputStream.readUByte(); + this.highDensityTrackJam = inputStream.readUByte(); + this.pad4 = inputStream.readUByte(); + this.jammingModeSequence = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfTrackJamTargets; idx++) + { + var anX = new dis.TrackJamTarget(); + anX.initFromBinary(inputStream); + this.trackJamTargets.push(anX); + } + + }; + + dis.ElectronicEmissionBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.beamParameterIndex); + this.fundamentalParameterData.encodeToBinary(outputStream); + outputStream.writeUByte(this.beamFunction); + outputStream.writeUByte(this.numberOfTrackJamTargets); + outputStream.writeUByte(this.highDensityTrackJam); + outputStream.writeUByte(this.pad4); + outputStream.writeUInt(this.jammingModeSequence); + for(var idx = 0; idx < this.trackJamTargets.length; idx++) + { + trackJamTargets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionBeamData = dis.ElectronicEmissionBeamData; + +// End of ElectronicEmissionBeamData class + +/** + * Data about one electronic system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionSystemData = function() +{ + /** This field shall specify the length of this emitter system�s data (including beam data and its track/jam information) in 32-bit words. The length shall include the System Data Length field. */ + this.systemDataLength = 0; + + /** This field shall specify the number of beams being described in the current PDU for the system being described. */ + this.numberOfBeams = 0; + + /** padding. */ + this.emissionsPadding2 = 0; + + /** This field shall specify information about a particular emitter system */ + this.emitterSystem = new dis.EmitterSystem(); + + /** Location with respect to the entity */ + this.location = new dis.Vector3Float(); + + /** variable length variablelist of beam data records */ + this.beamDataRecords = new Array(); + + dis.ElectronicEmissionSystemData.prototype.initFromBinary = function(inputStream) + { + this.systemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.emissionsPadding2 = inputStream.readUShort(); + this.emitterSystem.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.ElectronicEmissionBeamData(); + anX.initFromBinary(inputStream); + this.beamDataRecords.push(anX); + } + + }; + + dis.ElectronicEmissionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.emissionsPadding2); + this.emitterSystem.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamDataRecords.length; idx++) + { + beamDataRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionSystemData = dis.ElectronicEmissionSystemData; + +// End of ElectronicEmissionSystemData class + +/** + * Section 5.3.7.1. Information about active electronic warfare (EW) emissions and active EW countermeasures shall be communicated using an Electromagnetic Emission PDU. COMPLETE (I think) + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionsPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 23; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity emitting */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)]. */ + this.stateUpdateIndicator = 0; + + /** This field shall specify the number of emission systems being described in the current PDU. */ + this.numberOfSystems = 0; + + /** padding */ + this.paddingForEmissionsPdu = 0; + + /** Electronic emmissions systems */ + this.systems = new Array(); + + dis.ElectronicEmissionsPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateUpdateIndicator = inputStream.readUByte(); + this.numberOfSystems = inputStream.readUByte(); + this.paddingForEmissionsPdu = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfSystems; idx++) + { + var anX = new dis.ElectronicEmissionSystemData(); + anX.initFromBinary(inputStream); + this.systems.push(anX); + } + + }; + + dis.ElectronicEmissionsPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.stateUpdateIndicator); + outputStream.writeUByte(this.numberOfSystems); + outputStream.writeUShort(this.paddingForEmissionsPdu); + for(var idx = 0; idx < this.systems.length; idx++) + { + systems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionsPdu = dis.ElectronicEmissionsPdu; + +// End of ElectronicEmissionsPdu class + +/** + * Section 5.2.11. This field shall specify information about a particular emitter system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EmitterSystem = function() +{ + /** Name of the emitter, 16 bit enumeration */ + this.emitterName = 0; + + /** function of the emitter, 8 bit enumeration */ + this.function = 0; + + /** emitter ID, 8 bit enumeration */ + this.emitterIdNumber = 0; + + dis.EmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.emitterName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.emitterIdNumber = inputStream.readUByte(); + }; + + dis.EmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.emitterName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.emitterIdNumber); + }; +}; // end of class + + // node.js module support +exports.EmitterSystem = dis.EmitterSystem; + +// End of EmitterSystem class + +/** + * Each entity in a given DIS simulation application shall be given an entity identifier number unique to all other entities in that application. This identifier number is valid for the duration of the exercise; however, entity identifier numbers may be reused when all possible numbers have been exhausted. No entity shall have an entity identifier number of NO_ENTITY, ALL_ENTITIES, or RQST_ASSIGN_ID. The entity iden- tifier number need not be registered or retained for future exercises. The entity identifier number shall be specified by a 16-bit unsigned integer. An entity identifier number equal to zero with valid site and application identification shall address a simulation application. An entity identifier number equal to ALL_ENTITIES shall mean all entities within the specified site and application. An entity identifier number equal to RQST_ASSIGN_ID allows the receiver of the create entity to define the entity identifier number of the new entity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + dis.EntityID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + }; + + dis.EntityID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + }; +}; // end of class + + // node.js module support +exports.EntityID = dis.EntityID; + +// End of EntityID class + +/** + * Section 5.3.3. Common superclass for EntityState, Collision, collision-elastic, and entity state update PDUs. This should be abstract. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityInformationFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityInformationFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityInformationFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityInformationFamilyPdu = dis.EntityInformationFamilyPdu; + +// End of EntityInformationFamilyPdu class + +/** + * Section 5.3.9. Common superclass for EntityManagment PDUs, including aggregate state, isGroupOf, TransferControLRequest, and isPartOf + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityManagementFamilyPdu = dis.EntityManagementFamilyPdu; + +// End of EntityManagementFamilyPdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Unique ID for an entity that is tied to this state information */ + this.entityID = new dis.EntityID(); + + /** What force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the type of entity in the world */ + this.entityType = new dis.EntityType(); + + this.alternativeEntityType = new dis.EntityType(); + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** parameters used for dead reckoning */ + this.deadReckoningParameters = new dis.DeadReckoningParameter(); + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new dis.Marking(); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.EntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityType.initFromBinary(inputStream); + this.alternativeEntityType.initFromBinary(inputStream); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningParameters.initFromBinary(inputStream); + this.marking.initFromBinary(inputStream); + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + this.entityType.encodeToBinary(outputStream); + this.alternativeEntityType.encodeToBinary(outputStream); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + this.deadReckoningParameters.encodeToBinary(outputStream); + this.marking.encodeToBinary(outputStream); + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStatePdu = dis.EntityStatePdu; + +// End of EntityStatePdu class + +/** + * 5.3.3.4. Nonstatic information about a particular entity may be communicated by issuing an Entity State Update PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStateUpdatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 67; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** This field shall identify the entity issuing the PDU */ + this.entityID = new dis.EntityID(); + + /** Padding */ + this.padding1 = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + this.articulationParameters = new Array(); + + dis.EntityStateUpdatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.padding1 = inputStream.readByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStateUpdatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeByte(this.padding1); + outputStream.writeUByte(this.numberOfArticulationParameters); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStateUpdatePdu = dis.EntityStateUpdatePdu; + +// End of EntityStateUpdatePdu class + +/** + * Section 5.2.16. Identifies the type of entity, including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Renamed from specific because that is a reserved word in SQL */ + this.spec = 0; + + this.extra = 0; + + dis.EntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.spec = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.EntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.spec); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.EntityType = dis.EntityType; + +// End of EntityType class + +/** + * Section 5.2.40. Information about a geometry, a state associated with a geometry, a bounding volume, or an associated entity ID. NOTE: this class requires hand coding. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Environment = function() +{ + /** Record type */ + this.environmentType = 0; + + /** length, in bits */ + this.length = 0; + + /** Identify the sequentially numbered record index */ + this.recordIndex = 0; + + /** padding */ + this.padding1 = 0; + + /** Geometry or state record */ + this.geometry = 0; + + /** padding to bring the total size up to a 64 bit boundry */ + this.padding2 = 0; + + dis.Environment.prototype.initFromBinary = function(inputStream) + { + this.environmentType = inputStream.readUInt(); + this.length = inputStream.readUByte(); + this.recordIndex = inputStream.readUByte(); + this.padding1 = inputStream.readUByte(); + this.geometry = inputStream.readUByte(); + this.padding2 = inputStream.readUByte(); + }; + + dis.Environment.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.environmentType); + outputStream.writeUByte(this.length); + outputStream.writeUByte(this.recordIndex); + outputStream.writeUByte(this.padding1); + outputStream.writeUByte(this.geometry); + outputStream.writeUByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.Environment = dis.Environment; + +// End of Environment class + +/** + * Section 5.3.11.1: Information about environmental effects and processes. This requires manual cleanup. the environmental record is variable, as is the padding. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EnvironmentalProcessPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 41; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Environmental process ID */ + this.environementalProcessID = new dis.EntityID(); + + /** Environment type */ + this.environmentType = new dis.EntityType(); + + /** model type */ + this.modelType = 0; + + /** Environment status */ + this.environmentStatus = 0; + + /** number of environment records */ + this.numberOfEnvironmentRecords = 0; + + /** PDU sequence number for the environmentla process if pdu sequencing required */ + this.sequenceNumber = 0; + + /** environemt records */ + this.environmentRecords = new Array(); + + dis.EnvironmentalProcessPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environementalProcessID.initFromBinary(inputStream); + this.environmentType.initFromBinary(inputStream); + this.modelType = inputStream.readUByte(); + this.environmentStatus = inputStream.readUByte(); + this.numberOfEnvironmentRecords = inputStream.readUByte(); + this.sequenceNumber = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfEnvironmentRecords; idx++) + { + var anX = new dis.Environment(); + anX.initFromBinary(inputStream); + this.environmentRecords.push(anX); + } + + }; + + dis.EnvironmentalProcessPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environementalProcessID.encodeToBinary(outputStream); + this.environmentType.encodeToBinary(outputStream); + outputStream.writeUByte(this.modelType); + outputStream.writeUByte(this.environmentStatus); + outputStream.writeUByte(this.numberOfEnvironmentRecords); + outputStream.writeUShort(this.sequenceNumber); + for(var idx = 0; idx < this.environmentRecords.length; idx++) + { + environmentRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EnvironmentalProcessPdu = dis.EnvironmentalProcessPdu; + +// End of EnvironmentalProcessPdu class + +/** + * Section 5.2.18. Identifies a unique event in a simulation via the combination of three values + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the number of the event */ + this.eventNumber = 0; + + dis.EventID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.eventNumber = inputStream.readUShort(); + }; + + dis.EventID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.eventNumber); + }; +}; // end of class + + // node.js module support +exports.EventID = dis.EventID; + +// End of EventID class + +/** + * Section 5.3.6.11. Reports occurance of a significant event to the simulation manager. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 21; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Type of event */ + this.eventType = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.EventReportPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.EventReportPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.eventType); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportPdu = dis.EventReportPdu; + +// End of EventReportPdu class + +/** + * Section 5.3.12.11: reports the occurance of a significatnt event to the simulation manager. Needs manual intervention to fix padding in variable datums. UNFINISHED. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 61; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Event type */ + this.eventType = 0; + + /** padding */ + this.pad1 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.EventReportReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.EventReportReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.pad1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportReliablePdu = dis.EventReportReliablePdu; + +// End of EventReportReliablePdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. This is identical in function to entity state pdu, but generates less garbage to collect in the Java world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FastEntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + /** what force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Name changed from specific because that is a reserved word in SQL. */ + this.specif = 0; + + this.extra = 0; + + /** Kind of entity */ + this.altEntityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.altDomain = 0; + + /** country to which the design of the entity is attributed */ + this.altCountry = 0; + + /** category of entity */ + this.altCategory = 0; + + /** subcategory of entity */ + this.altSubcategory = 0; + + /** specific info based on subcategory field */ + this.altSpecific = 0; + + this.altExtra = 0; + + /** X velo */ + this.xVelocity = 0; + + /** y Value */ + this.yVelocity = 0; + + /** Z value */ + this.zVelocity = 0; + + /** X value */ + this.xLocation = 0; + + /** y Value */ + this.yLocation = 0; + + /** Z value */ + this.zLocation = 0; + + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** X value */ + this.xAcceleration = 0; + + /** y Value */ + this.yAcceleration = 0; + + /** Z value */ + this.zAcceleration = 0; + + /** X value */ + this.xAngularVelocity = 0; + + /** y Value */ + this.yAngularVelocity = 0; + + /** Z value */ + this.zAngularVelocity = 0; + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.FastEntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specif = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + this.altEntityKind = inputStream.readUByte(); + this.altDomain = inputStream.readUByte(); + this.altCountry = inputStream.readUShort(); + this.altCategory = inputStream.readUByte(); + this.altSubcategory = inputStream.readUByte(); + this.altSpecific = inputStream.readUByte(); + this.altExtra = inputStream.readUByte(); + this.xVelocity = inputStream.readFloat32(); + this.yVelocity = inputStream.readFloat32(); + this.zVelocity = inputStream.readFloat32(); + this.xLocation = inputStream.readFloat64(); + this.yLocation = inputStream.readFloat64(); + this.zLocation = inputStream.readFloat64(); + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.xAcceleration = inputStream.readFloat32(); + this.yAcceleration = inputStream.readFloat32(); + this.zAcceleration = inputStream.readFloat32(); + this.xAngularVelocity = inputStream.readFloat32(); + this.yAngularVelocity = inputStream.readFloat32(); + this.zAngularVelocity = inputStream.readFloat32(); + for(var idx = 0; idx < 12; idx++) + { + this.marking[ idx ] = inputStream.readByte(); + } + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.FastEntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specif); + outputStream.writeUByte(this.extra); + outputStream.writeUByte(this.altEntityKind); + outputStream.writeUByte(this.altDomain); + outputStream.writeUShort(this.altCountry); + outputStream.writeUByte(this.altCategory); + outputStream.writeUByte(this.altSubcategory); + outputStream.writeUByte(this.altSpecific); + outputStream.writeUByte(this.altExtra); + outputStream.writeFloat32(this.xVelocity); + outputStream.writeFloat32(this.yVelocity); + outputStream.writeFloat32(this.zVelocity); + outputStream.writeFloat64(this.xLocation); + outputStream.writeFloat64(this.yLocation); + outputStream.writeFloat64(this.zLocation); + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + outputStream.writeInt(this.entityAppearance); + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + outputStream.writeFloat32(this.xAcceleration); + outputStream.writeFloat32(this.yAcceleration); + outputStream.writeFloat32(this.zAcceleration); + outputStream.writeFloat32(this.xAngularVelocity); + outputStream.writeFloat32(this.yAngularVelocity); + outputStream.writeFloat32(this.zAngularVelocity); + for(var idx = 0; idx < 12; idx++) + { + outputStream.writeByte(this.marking[ idx ] ); + } + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.FastEntityStatePdu = dis.FastEntityStatePdu; + +// End of FastEntityStatePdu class + +/** + * Sectioin 5.3.4.1. Information about someone firing something. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FirePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 2; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of the munition that is being shot */ + this.munitionID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + this.fireMissionIndex = 0; + + /** location of the firing event */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munitions used in the firing event */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** Velocity of the ammunition */ + this.velocity = new dis.Vector3Float(); + + /** range to the target. Note the word range is a SQL reserved word. */ + this.rangeToTarget = 0; + + dis.FirePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.fireMissionIndex = inputStream.readInt(); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.rangeToTarget = inputStream.readFloat32(); + }; + + dis.FirePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeInt(this.fireMissionIndex); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.rangeToTarget); + }; +}; // end of class + + // node.js module support +exports.FirePdu = dis.FirePdu; + +// End of FirePdu class + +/** + * Section 5.2.18. Fixed Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FixedDatum = function() +{ + /** ID of the fixed datum */ + this.fixedDatumID = 0; + + /** Value for the fixed datum */ + this.fixedDatumValue = 0; + + dis.FixedDatum.prototype.initFromBinary = function(inputStream) + { + this.fixedDatumID = inputStream.readUInt(); + this.fixedDatumValue = inputStream.readUInt(); + }; + + dis.FixedDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.fixedDatumID); + outputStream.writeUInt(this.fixedDatumValue); + }; +}; // end of class + + // node.js module support +exports.FixedDatum = dis.FixedDatum; + +// End of FixedDatum class + +/** + * 32 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FourByteChunk = function() +{ + /** four bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0); + + dis.FourByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 4; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.FourByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 4; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.FourByteChunk = dis.FourByteChunk; + +// End of FourByteChunk class + +/** + * Section 5.2.22. Contains electromagnetic emmision regineratin parameters that are variable throughout a scenario dependent on the actions of the participants in the simulation. Also provides basic parametric data that may be used to support low-fidelity simulations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterData = function() +{ + /** center frequency of the emission in hertz. */ + this.frequency = 0; + + /** Bandwidth of the frequencies corresponding to the fequency field. */ + this.frequencyRange = 0; + + /** Effective radiated power for the emission in DdBm. For a radar noise jammer, indicates the peak of the transmitted power. */ + this.effectiveRadiatedPower = 0; + + /** Average repetition frequency of the emission in hertz. */ + this.pulseRepetitionFrequency = 0; + + /** Average pulse width of the emission in microseconds. */ + this.pulseWidth = 0; + + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.FundamentalParameterData.prototype.initFromBinary = function(inputStream) + { + this.frequency = inputStream.readFloat32(); + this.frequencyRange = inputStream.readFloat32(); + this.effectiveRadiatedPower = inputStream.readFloat32(); + this.pulseRepetitionFrequency = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.FundamentalParameterData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.frequencyRange); + outputStream.writeFloat32(this.effectiveRadiatedPower); + outputStream.writeFloat32(this.pulseRepetitionFrequency); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterData = dis.FundamentalParameterData; + +// End of FundamentalParameterData class + +/** + * 5.2.45. Fundamental IFF atc data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterDataIff = function() +{ + /** ERP */ + this.erp = 0; + + /** frequency */ + this.frequency = 0; + + /** pgrf */ + this.pgrf = 0; + + /** Pulse width */ + this.pulseWidth = 0; + + /** Burst length */ + this.burstLength = 0; + + /** Applicable modes enumeration */ + this.applicableModes = 0; + + /** padding */ + this.pad2 = 0; + + /** padding */ + this.pad3 = 0; + + dis.FundamentalParameterDataIff.prototype.initFromBinary = function(inputStream) + { + this.erp = inputStream.readFloat32(); + this.frequency = inputStream.readFloat32(); + this.pgrf = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.burstLength = inputStream.readUInt(); + this.applicableModes = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.pad3 = inputStream.readUByte(); + }; + + dis.FundamentalParameterDataIff.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.erp); + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.pgrf); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeUInt(this.burstLength); + outputStream.writeUByte(this.applicableModes); + outputStream.writeUShort(this.pad2); + outputStream.writeUByte(this.pad3); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterDataIff = dis.FundamentalParameterDataIff; + +// End of FundamentalParameterDataIff class + +/** + * 5.2.44: Grid data record, a common abstract superclass for several subtypes + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecord = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + dis.GridAxisRecord.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + }; + + dis.GridAxisRecord.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + }; +}; // end of class + + // node.js module support +exports.GridAxisRecord = dis.GridAxisRecord; + +// End of GridAxisRecord class + +/** + * 5.2.44: Grid data record, representation 0 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation0 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of bytes of environmental state data */ + this.numberOfBytes = 0; + + /** variable length variablelist of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation0.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfBytes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfBytes; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation0.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfBytes); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation0 = dis.GridAxisRecordRepresentation0; + +// End of GridAxisRecordRepresentation0 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation1 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** constant scale factor */ + this.fieldScale = 0; + + /** constant offset used to scale grid data */ + this.fieldOffset = 0; + + /** Number of data values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation1.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.fieldScale = inputStream.readFloat32(); + this.fieldOffset = inputStream.readFloat32(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation1.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeFloat32(this.fieldScale); + outputStream.writeFloat32(this.fieldOffset); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation1 = dis.GridAxisRecordRepresentation1; + +// End of GridAxisRecordRepresentation1 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation2 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation2.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation2.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation2 = dis.GridAxisRecordRepresentation2; + +// End of GridAxisRecordRepresentation2 class + +/** + * Section 5.3.11.2: Information about globat, spatially varying enviornmental effects. This requires manual cleanup; the grid axis records are variable sized. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GriddedDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 42; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** environmental simulation application ID */ + this.environmentalSimulationApplicationID = new dis.EntityID(); + + /** unique identifier for each piece of enviornmental data */ + this.fieldNumber = 0; + + /** sequence number for the total set of PDUS used to transmit the data */ + this.pduNumber = 0; + + /** Total number of PDUS used to transmit the data */ + this.pduTotal = 0; + + /** coordinate system of the grid */ + this.coordinateSystem = 0; + + /** number of grid axes for the environmental data */ + this.numberOfGridAxes = 0; + + /** are domain grid axes identidal to those of the priveious domain update? */ + this.constantGrid = 0; + + /** type of environment */ + this.environmentType = new dis.EntityType(); + + /** orientation of the data grid */ + this.orientation = new dis.Orientation(); + + /** valid time of the enviormental data sample, 64 bit unsigned int */ + this.sampleTime = 0; + + /** total number of all data values for all pdus for an environmental sample */ + this.totalValues = 0; + + /** total number of data values at each grid point. */ + this.vectorDimension = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** Grid data ^^^This is wrong */ + this.gridDataList = new Array(); + + dis.GriddedDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environmentalSimulationApplicationID.initFromBinary(inputStream); + this.fieldNumber = inputStream.readUShort(); + this.pduNumber = inputStream.readUShort(); + this.pduTotal = inputStream.readUShort(); + this.coordinateSystem = inputStream.readUShort(); + this.numberOfGridAxes = inputStream.readUByte(); + this.constantGrid = inputStream.readUByte(); + this.environmentType.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.sampleTime = inputStream.readLong(); + this.totalValues = inputStream.readUInt(); + this.vectorDimension = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfGridAxes; idx++) + { + var anX = new dis.GridAxisRecord(); + anX.initFromBinary(inputStream); + this.gridDataList.push(anX); + } + + }; + + dis.GriddedDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environmentalSimulationApplicationID.encodeToBinary(outputStream); + outputStream.writeUShort(this.fieldNumber); + outputStream.writeUShort(this.pduNumber); + outputStream.writeUShort(this.pduTotal); + outputStream.writeUShort(this.coordinateSystem); + outputStream.writeUByte(this.numberOfGridAxes); + outputStream.writeUByte(this.constantGrid); + this.environmentType.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeLong(this.sampleTime); + outputStream.writeUInt(this.totalValues); + outputStream.writeUByte(this.vectorDimension); + outputStream.writeUShort(this.padding1); + outputStream.writeUByte(this.padding2); + for(var idx = 0; idx < this.gridDataList.length; idx++) + { + gridDataList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GriddedDataPdu = dis.GriddedDataPdu; + +// End of GriddedDataPdu class + +/** + * 5.3.7.4.1: Navigational and IFF PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer1Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + dis.IffAtcNavAidsLayer1Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + }; + + dis.IffAtcNavAidsLayer1Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer1Pdu = dis.IffAtcNavAidsLayer1Pdu; + +// End of IffAtcNavAidsLayer1Pdu class + +/** + * Section 5.3.7.4.2 When present, layer 2 should follow layer 1 and have the following fields. This requires manual cleanup. the beamData attribute semantics are used in multiple ways. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer2Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + /** layer header */ + this.layerHeader = new dis.LayerHeader(); + + /** beam data */ + this.beamData = new dis.BeamData(); + + /** Secondary operational data, 5.2.57 */ + this.secondaryOperationalData = new dis.BeamData(); + + /** variable length list of fundamental parameters. ^^^This is wrong */ + this.fundamentalIffParameters = new Array(); + + dis.IffAtcNavAidsLayer2Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + this.layerHeader.initFromBinary(inputStream); + this.beamData.initFromBinary(inputStream); + this.secondaryOperationalData.initFromBinary(inputStream); + for(var idx = 0; idx < this.pad2; idx++) + { + var anX = new dis.FundamentalParameterDataIff(); + anX.initFromBinary(inputStream); + this.fundamentalIffParameters.push(anX); + } + + }; + + dis.IffAtcNavAidsLayer2Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + this.layerHeader.encodeToBinary(outputStream); + this.beamData.encodeToBinary(outputStream); + this.secondaryOperationalData.encodeToBinary(outputStream); + for(var idx = 0; idx < this.fundamentalIffParameters.length; idx++) + { + fundamentalIffParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer2Pdu = dis.IffAtcNavAidsLayer2Pdu; + +// End of IffAtcNavAidsLayer2Pdu class + +/** + * 5.2.42. Basic operational data ofr IFF ATC NAVAIDS + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffFundamentalData = function() +{ + /** system status */ + this.systemStatus = 0; + + /** Alternate parameter 4 */ + this.alternateParameter4 = 0; + + /** eight boolean fields */ + this.informationLayers = 0; + + /** enumeration */ + this.modifier = 0; + + /** parameter, enumeration */ + this.parameter1 = 0; + + /** parameter, enumeration */ + this.parameter2 = 0; + + /** parameter, enumeration */ + this.parameter3 = 0; + + /** parameter, enumeration */ + this.parameter4 = 0; + + /** parameter, enumeration */ + this.parameter5 = 0; + + /** parameter, enumeration */ + this.parameter6 = 0; + + dis.IffFundamentalData.prototype.initFromBinary = function(inputStream) + { + this.systemStatus = inputStream.readUByte(); + this.alternateParameter4 = inputStream.readUByte(); + this.informationLayers = inputStream.readUByte(); + this.modifier = inputStream.readUByte(); + this.parameter1 = inputStream.readUShort(); + this.parameter2 = inputStream.readUShort(); + this.parameter3 = inputStream.readUShort(); + this.parameter4 = inputStream.readUShort(); + this.parameter5 = inputStream.readUShort(); + this.parameter6 = inputStream.readUShort(); + }; + + dis.IffFundamentalData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemStatus); + outputStream.writeUByte(this.alternateParameter4); + outputStream.writeUByte(this.informationLayers); + outputStream.writeUByte(this.modifier); + outputStream.writeUShort(this.parameter1); + outputStream.writeUShort(this.parameter2); + outputStream.writeUShort(this.parameter3); + outputStream.writeUShort(this.parameter4); + outputStream.writeUShort(this.parameter5); + outputStream.writeUShort(this.parameter6); + }; +}; // end of class + + // node.js module support +exports.IffFundamentalData = dis.IffFundamentalData; + +// End of IffFundamentalData class + +/** + * 5.2.46. Intercom communcations parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomCommunicationsParameters = function() +{ + /** Type of intercom parameters record */ + this.recordType = 0; + + /** length of record-specifid field, in octets */ + this.recordLength = 0; + + /** variable length variablelist of data parameters */ + this.parameterValues = new Array(); + + dis.IntercomCommunicationsParameters.prototype.initFromBinary = function(inputStream) + { + this.recordType = inputStream.readUShort(); + this.recordLength = inputStream.readUShort(); + for(var idx = 0; idx < this.recordLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.parameterValues.push(anX); + } + + }; + + dis.IntercomCommunicationsParameters.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.recordType); + outputStream.writeUShort(this.recordLength); + for(var idx = 0; idx < this.parameterValues.length; idx++) + { + parameterValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomCommunicationsParameters = dis.IntercomCommunicationsParameters; + +// End of IntercomCommunicationsParameters class + +/** + * Section 5.3.8.5. Detailed inofrmation about the state of an intercom device and the actions it is requestion of another intercom device, or the response to a requested action. Required manual intervention to fix the intercom parameters, which can be of varialbe length. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomControlPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 32; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** control type */ + this.controlType = 0; + + /** control type */ + this.communicationsChannelType = 0; + + /** Source entity ID */ + this.sourceEntityID = new dis.EntityID(); + + /** The specific intercom device being simulated within an entity. */ + this.sourceCommunicationsDeviceID = 0; + + /** Line number to which the intercom control refers */ + this.sourceLineID = 0; + + /** priority of this message relative to transmissons from other intercom devices */ + this.transmitPriority = 0; + + /** current transmit state of the line */ + this.transmitLineState = 0; + + /** detailed type requested. */ + this.command = 0; + + /** eid of the entity that has created this intercom channel. */ + this.masterEntityID = new dis.EntityID(); + + /** specific intercom device that has created this intercom channel */ + this.masterCommunicationsDeviceID = 0; + + /** number of intercom parameters */ + this.intercomParametersLength = 0; + + /** Must be */ + this.intercomParameters = new Array(); + + dis.IntercomControlPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.controlType = inputStream.readUByte(); + this.communicationsChannelType = inputStream.readUByte(); + this.sourceEntityID.initFromBinary(inputStream); + this.sourceCommunicationsDeviceID = inputStream.readUByte(); + this.sourceLineID = inputStream.readUByte(); + this.transmitPriority = inputStream.readUByte(); + this.transmitLineState = inputStream.readUByte(); + this.command = inputStream.readUByte(); + this.masterEntityID.initFromBinary(inputStream); + this.masterCommunicationsDeviceID = inputStream.readUShort(); + this.intercomParametersLength = inputStream.readUInt(); + for(var idx = 0; idx < this.intercomParametersLength; idx++) + { + var anX = new dis.IntercomCommunicationsParameters(); + anX.initFromBinary(inputStream); + this.intercomParameters.push(anX); + } + + }; + + dis.IntercomControlPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUByte(this.controlType); + outputStream.writeUByte(this.communicationsChannelType); + this.sourceEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.sourceCommunicationsDeviceID); + outputStream.writeUByte(this.sourceLineID); + outputStream.writeUByte(this.transmitPriority); + outputStream.writeUByte(this.transmitLineState); + outputStream.writeUByte(this.command); + this.masterEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.masterCommunicationsDeviceID); + outputStream.writeUInt(this.intercomParametersLength); + for(var idx = 0; idx < this.intercomParameters.length; idx++) + { + intercomParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomControlPdu = dis.IntercomControlPdu; + +// End of IntercomControlPdu class + +/** + * Section 5.3.8.4. Actual transmission of intercome voice data. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomSignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 31; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entitythat is the source of the communication */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.communicationsDeviceID = 0; + + /** encoding scheme */ + this.encodingScheme = 0; + + /** tactical data link type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** data length, in bits */ + this.dataLength = 0; + + /** samples */ + this.samples = 0; + + /** data bytes */ + this.data = new Array(); + + dis.IntercomSignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.communicationsDeviceID = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.IntercomSignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.communicationsDeviceID); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomSignalPdu = dis.IntercomSignalPdu; + +// End of IntercomSignalPdu class + +/** + * Section 5.3.9.2 Information about a particular group of entities grouped together for the purposes of netowrk bandwidth reduction or aggregation. Needs manual cleanup. The GED size requires a database lookup. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsGroupOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 34; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.groupEntityID = new dis.EntityID(); + + /** type of entities constituting the group */ + this.groupedEntityCategory = 0; + + /** Number of individual entities constituting the group */ + this.numberOfGroupedEntities = 0; + + /** padding */ + this.pad2 = 0; + + /** latitude */ + this.latitude = 0; + + /** longitude */ + this.longitude = 0; + + /** GED records about each individual entity in the group. ^^^this is wrong--need a database lookup to find the actual size of the list elements */ + this.groupedEntityDescriptions = new Array(); + + dis.IsGroupOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.groupEntityID.initFromBinary(inputStream); + this.groupedEntityCategory = inputStream.readUByte(); + this.numberOfGroupedEntities = inputStream.readUByte(); + this.pad2 = inputStream.readUInt(); + this.latitude = inputStream.readFloat64(); + this.longitude = inputStream.readFloat64(); + for(var idx = 0; idx < this.numberOfGroupedEntities; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.groupedEntityDescriptions.push(anX); + } + + }; + + dis.IsGroupOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.groupEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.groupedEntityCategory); + outputStream.writeUByte(this.numberOfGroupedEntities); + outputStream.writeUInt(this.pad2); + outputStream.writeFloat64(this.latitude); + outputStream.writeFloat64(this.longitude); + for(var idx = 0; idx < this.groupedEntityDescriptions.length; idx++) + { + groupedEntityDescriptions[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IsGroupOfPdu = dis.IsGroupOfPdu; + +// End of IsGroupOfPdu class + +/** + * Section 5.3.9.4 The joining of two or more simulation entities is communicated by this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsPartOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 36; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating PDU */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving PDU */ + this.receivingEntityID = new dis.EntityID(); + + /** relationship of joined parts */ + this.relationship = new dis.Relationship(); + + /** location of part; centroid of part in host's coordinate system. x=range, y=bearing, z=0 */ + this.partLocation = new dis.Vector3Float(); + + /** named location */ + this.namedLocationID = new dis.NamedLocation(); + + /** entity type */ + this.partEntityType = new dis.EntityType(); + + dis.IsPartOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.relationship.initFromBinary(inputStream); + this.partLocation.initFromBinary(inputStream); + this.namedLocationID.initFromBinary(inputStream); + this.partEntityType.initFromBinary(inputStream); + }; + + dis.IsPartOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.relationship.encodeToBinary(outputStream); + this.partLocation.encodeToBinary(outputStream); + this.namedLocationID.encodeToBinary(outputStream); + this.partEntityType.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IsPartOfPdu = dis.IsPartOfPdu; + +// End of IsPartOfPdu class + +/** + * 5.2.47. Layer header. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LayerHeader = function() +{ + /** Layer number */ + this.layerNumber = 0; + + /** Layer speccific information enumeration */ + this.layerSpecificInformaiton = 0; + + /** information length */ + this.length = 0; + + dis.LayerHeader.prototype.initFromBinary = function(inputStream) + { + this.layerNumber = inputStream.readUByte(); + this.layerSpecificInformaiton = inputStream.readUByte(); + this.length = inputStream.readUShort(); + }; + + dis.LayerHeader.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.layerNumber); + outputStream.writeUByte(this.layerSpecificInformaiton); + outputStream.writeUShort(this.length); + }; +}; // end of class + + // node.js module support +exports.LayerHeader = dis.LayerHeader; + +// End of LayerHeader class + +/** + * Section 5.3.11.4: Information abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point and has size or orientation. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 44; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** number of linear segment parameters */ + this.numberOfSegments = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Linear segment parameters */ + this.linearSegmentParameters = new Array(); + + dis.LinearObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfSegments = inputStream.readUByte(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.objectType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSegments; idx++) + { + var anX = new dis.LinearSegmentParameter(); + anX.initFromBinary(inputStream); + this.linearSegmentParameters.push(anX); + } + + }; + + dis.LinearObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfSegments); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + this.objectType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.linearSegmentParameters.length; idx++) + { + linearSegmentParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.LinearObjectStatePdu = dis.LinearObjectStatePdu; + +// End of LinearObjectStatePdu class + +/** + * 5.2.48: Linear segment parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearSegmentParameter = function() +{ + /** number of segments */ + this.segmentNumber = 0; + + /** segment appearance */ + this.segmentAppearance = new dis.SixByteChunk(); + + /** location */ + this.location = new dis.Vector3Double(); + + /** orientation */ + this.orientation = new dis.Orientation(); + + /** segmentLength */ + this.segmentLength = 0; + + /** segmentWidth */ + this.segmentWidth = 0; + + /** segmentHeight */ + this.segmentHeight = 0; + + /** segment Depth */ + this.segmentDepth = 0; + + /** segment Depth */ + this.pad1 = 0; + + dis.LinearSegmentParameter.prototype.initFromBinary = function(inputStream) + { + this.segmentNumber = inputStream.readUByte(); + this.segmentAppearance.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.segmentLength = inputStream.readUShort(); + this.segmentWidth = inputStream.readUShort(); + this.segmentHeight = inputStream.readUShort(); + this.segmentDepth = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + }; + + dis.LinearSegmentParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.segmentNumber); + this.segmentAppearance.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.segmentLength); + outputStream.writeUShort(this.segmentWidth); + outputStream.writeUShort(this.segmentHeight); + outputStream.writeUShort(this.segmentDepth); + outputStream.writeUInt(this.pad1); + }; +}; // end of class + + // node.js module support +exports.LinearSegmentParameter = dis.LinearSegmentParameter; + +// End of LinearSegmentParameter class + +/** + * Section 5.3.5. Abstract superclass for logistics PDUs. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LogisticsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.LogisticsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.LogisticsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.LogisticsFamilyPdu = dis.LogisticsFamilyPdu; + +// End of LogisticsFamilyPdu class + +/** + * Section 5.2.15. Specifies the character set used inthe first byte, followed by 11 characters of text data. + * The generated Marking class should be augmented with a patch that adds getMarking() and + * setMarking() methods that convert between arrays and strings, and clamp the length + * of the string to 11 characters. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Marking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.Marking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 11; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.Marking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 11; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; + + /* + * Returns the byte array marking, in string format. + * @return string format marking characters + */ + dis.Marking.prototype.getMarking = function() + { + var marking = ""; + for(var idx = 0; idx < 11; idx++) + { + marking = marking + String.fromCharCode(this.characters[idx]); + } + + return marking; + }; + + /** + * Given a string format marking, sets the bytes of the marking object + * to the appropriate character values. Clamps the string to no more + * than 11 characters. + * + * @param {String} newMarking string format marking + * @returns {nothing} + */ + dis.Marking.prototype.setMarking = function(newMarking) + { + var stringLen = newMarking.length; + if(stringLen > 11) + stringLen = 11; + + // Copy over up to 11 characters from the string to the array + var charsCopied = 0; + while(charsCopied < stringLen) + { + this.characters[charsCopied] = newMarking.charCodeAt( charsCopied ); + charsCopied++; + } + + // Zero-fill the remainer of the character array + while(charsCopied < 11) + { + this.characters[ charsCopied ] = 0; + charsCopied++; + } + + }; +}; // end of class + + // node.js module support +exports.Marking = dis.Marking; + +// End of Marking class + +/** + * Section 5.3.10.3 Information about individual mines within a minefield. This is very, very wrong. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 39; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** ID of entity making request */ + this.requestingEntityID = new dis.EntityID(); + + /** Minefield sequence number */ + this.minefieldSequenceNumbeer = 0; + + /** request ID */ + this.requestID = 0; + + /** pdu sequence number */ + this.pduSequenceNumber = 0; + + /** number of pdus in response */ + this.numberOfPdus = 0; + + /** how many mines are in this PDU */ + this.numberOfMinesInThisPdu = 0; + + /** how many sensor type are in this PDU */ + this.numberOfSensorTypes = 0; + + /** padding */ + this.pad2 = 0; + + /** 32 boolean fields */ + this.dataFilter = 0; + + /** Mine type */ + this.mineType = new dis.EntityType(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + /** Padding to get things 32-bit aligned. ^^^this is wrong--dyanmically sized padding needed */ + this.pad3 = 0; + + /** Mine locations */ + this.mineLocation = new Array(); + + dis.MinefieldDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.minefieldSequenceNumbeer = inputStream.readUShort(); + this.requestID = inputStream.readUByte(); + this.pduSequenceNumber = inputStream.readUByte(); + this.numberOfPdus = inputStream.readUByte(); + this.numberOfMinesInThisPdu = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.mineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + this.pad3 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMinesInThisPdu; idx++) + { + var anX = new dis.Vector3Float(); + anX.initFromBinary(inputStream); + this.mineLocation.push(anX); + } + + }; + + dis.MinefieldDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequenceNumbeer); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.pduSequenceNumber); + outputStream.writeUByte(this.numberOfPdus); + outputStream.writeUByte(this.numberOfMinesInThisPdu); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.dataFilter); + this.mineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad3); + for(var idx = 0; idx < this.mineLocation.length; idx++) + { + mineLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldDataPdu = dis.MinefieldDataPdu; + +// End of MinefieldDataPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.MinefieldFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.MinefieldFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.MinefieldFamilyPdu = dis.MinefieldFamilyPdu; + +// End of MinefieldFamilyPdu class + +/** + * Section 5.3.10.2 Query a minefield for information about individual mines. Requires manual clean up to get the padding right. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 38; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** EID of entity making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** Number of perimeter points for the minefield */ + this.numberOfPerimeterPoints = 0; + + /** Padding */ + this.pad2 = 0; + + /** Number of sensor types */ + this.numberOfSensorTypes = 0; + + /** data filter, 32 boolean fields */ + this.dataFilter = 0; + + /** Entity type of mine being requested */ + this.requestedMineType = new dis.EntityType(); + + /** perimeter points of request */ + this.requestedPerimeterPoints = new Array(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + dis.MinefieldQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.requestedMineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.requestedPerimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + }; + + dis.MinefieldQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + outputStream.writeUByte(this.pad2); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUInt(this.dataFilter); + this.requestedMineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.requestedPerimeterPoints.length; idx++) + { + requestedPerimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldQueryPdu = dis.MinefieldQueryPdu; + +// End of MinefieldQueryPdu class + +/** + * Section 5.3.10.4 proivde the means to request a retransmit of a minefield data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldResponseNackPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 40; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** entity ID making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** how many pdus were missing */ + this.numberOfMissingPdus = 0; + + /** PDU sequence numbers that were missing */ + this.missingPduSequenceNumbers = new Array(); + + dis.MinefieldResponseNackPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfMissingPdus = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMissingPdus; idx++) + { + var anX = new dis.EightByteChunk(); + anX.initFromBinary(inputStream); + this.missingPduSequenceNumbers.push(anX); + } + + }; + + dis.MinefieldResponseNackPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfMissingPdus); + for(var idx = 0; idx < this.missingPduSequenceNumbers.length; idx++) + { + missingPduSequenceNumbers[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldResponseNackPdu = dis.MinefieldResponseNackPdu; + +// End of MinefieldResponseNackPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 37; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** Minefield sequence */ + this.minefieldSequence = 0; + + /** force ID */ + this.forceID = 0; + + /** Number of permieter points */ + this.numberOfPerimeterPoints = 0; + + /** type of minefield */ + this.minefieldType = new dis.EntityType(); + + /** how many mine types */ + this.numberOfMineTypes = 0; + + /** location of minefield in world coords */ + this.minefieldLocation = new dis.Vector3Double(); + + /** orientation of minefield */ + this.minefieldOrientation = new dis.Orientation(); + + /** appearance bitflags */ + this.appearance = 0; + + /** protocolMode */ + this.protocolMode = 0; + + /** perimeter points for the minefield */ + this.perimeterPoints = new Array(); + + /** Type of mines */ + this.mineType = new Array(); + + dis.MinefieldStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.minefieldSequence = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.minefieldType.initFromBinary(inputStream); + this.numberOfMineTypes = inputStream.readUShort(); + this.minefieldLocation.initFromBinary(inputStream); + this.minefieldOrientation.initFromBinary(inputStream); + this.appearance = inputStream.readUShort(); + this.protocolMode = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.perimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfMineTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.mineType.push(anX); + } + + }; + + dis.MinefieldStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequence); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + this.minefieldType.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfMineTypes); + this.minefieldLocation.encodeToBinary(outputStream); + this.minefieldOrientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.appearance); + outputStream.writeUShort(this.protocolMode); + for(var idx = 0; idx < this.perimeterPoints.length; idx++) + { + perimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.mineType.length; idx++) + { + mineType[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldStatePdu = dis.MinefieldStatePdu; + +// End of MinefieldStatePdu class + +/** + * Radio modulation + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ModulationType = function() +{ + /** spread spectrum, 16 bit boolean array */ + this.spreadSpectrum = 0; + + /** major */ + this.major = 0; + + /** detail */ + this.detail = 0; + + /** system */ + this.system = 0; + + dis.ModulationType.prototype.initFromBinary = function(inputStream) + { + this.spreadSpectrum = inputStream.readUShort(); + this.major = inputStream.readUShort(); + this.detail = inputStream.readUShort(); + this.system = inputStream.readUShort(); + }; + + dis.ModulationType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.spreadSpectrum); + outputStream.writeUShort(this.major); + outputStream.writeUShort(this.detail); + outputStream.writeUShort(this.system); + }; +}; // end of class + + // node.js module support +exports.ModulationType = dis.ModulationType; + +// End of ModulationType class + +/** + * discrete ostional relationsihip + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.NamedLocation = function() +{ + /** station name enumeration */ + this.stationName = 0; + + /** station number */ + this.stationNumber = 0; + + dis.NamedLocation.prototype.initFromBinary = function(inputStream) + { + this.stationName = inputStream.readUShort(); + this.stationNumber = inputStream.readUShort(); + }; + + dis.NamedLocation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.stationName); + outputStream.writeUShort(this.stationNumber); + }; +}; // end of class + + // node.js module support +exports.NamedLocation = dis.NamedLocation; + +// End of NamedLocation class + +/** + * Identifies type of object. This is a shorter version of EntityType that omits the specific and extra fields. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ObjectType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + dis.ObjectType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + }; + + dis.ObjectType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + }; +}; // end of class + + // node.js module support +exports.ObjectType = dis.ObjectType; + +// End of ObjectType class + +/** + * 8 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.OneByteChunk = function() +{ + /** one byte of arbitrary data */ + this.otherParameters = new Array(0); + + dis.OneByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 1; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.OneByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 1; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.OneByteChunk = dis.OneByteChunk; + +// End of OneByteChunk class + +/** + * Section 5.2.17. Three floating point values representing an orientation, psi, theta, and phi, aka the euler angles, in radians + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Orientation = function() +{ + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + dis.Orientation.prototype.initFromBinary = function(inputStream) + { + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + }; + + dis.Orientation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + }; +}; // end of class + + // node.js module support +exports.Orientation = dis.Orientation; + +// End of Orientation class + +/** + * The superclass for all PDUs. This incorporates the PduHeader record, section 5.2.29. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 0; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.Pdu = dis.Pdu; + +// End of Pdu class + +/** + * A container that holds PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduContainer = function() +{ + /** Number of PDUs in the container list */ + this.numberOfPdus = 0; + + /** List of PDUs */ + this.pdus = new Array(); + + dis.PduContainer.prototype.initFromBinary = function(inputStream) + { + this.numberOfPdus = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfPdus; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdus.push(anX); + } + + }; + + dis.PduContainer.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.numberOfPdus); + for(var idx = 0; idx < this.pdus.length; idx++) + { + pdus[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduContainer = dis.PduContainer; + +// End of PduContainer class + +/** + * Non-DIS class, used to describe streams of PDUs when logging to SQL databases + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduStream = function() +{ + /** short description of this PDU stream */ + this.shortDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Longish description of this PDU stream */ + this.longDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Name of person performing recording */ + this.personRecording = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Email of person performing recording */ + this.authorEmail = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Start time of recording, in Unix time */ + this.startTime = 0; + + /** stop time of recording, in Unix time */ + this.stopTime = 0; + + /** how many PDUs in this stream */ + this.pduCount = 0; + + /** variable length list of PDUs */ + this.pdusInStream = new Array(); + + dis.PduStream.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 256; idx++) + { + this.shortDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 512; idx++) + { + this.longDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.personRecording[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.authorEmail[ idx ] = inputStream.readByte(); + } + this.startTime = inputStream.readLong(); + this.stopTime = inputStream.readLong(); + this.pduCount = inputStream.readUInt(); + for(var idx = 0; idx < this.pduCount; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdusInStream.push(anX); + } + + }; + + dis.PduStream.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 256; idx++) + { + outputStream.writeByte(this.shortDescription[ idx ] ); + } + for(var idx = 0; idx < 512; idx++) + { + outputStream.writeByte(this.longDescription[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.personRecording[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.authorEmail[ idx ] ); + } + outputStream.writeLong(this.startTime); + outputStream.writeLong(this.stopTime); + outputStream.writeUInt(this.pduCount); + for(var idx = 0; idx < this.pdusInStream.length; idx++) + { + pdusInStream[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduStream = dis.PduStream; + +// End of PduStream class + +/** + * x,y point + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Point = function() +{ + /** x */ + this.x = 0; + + /** y */ + this.y = 0; + + dis.Point.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + }; + + dis.Point.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + }; +}; // end of class + + // node.js module support +exports.Point = dis.Point; + +// End of Point class + +/** + * Section 5.3.11.3: Inormation abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PointObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 43; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Object location */ + this.objectLocation = new dis.Vector3Double(); + + /** Object orientation */ + this.objectOrientation = new dis.Orientation(); + + /** Object apperance */ + this.objectAppearance = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** padding */ + this.pad2 = 0; + + dis.PointObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectLocation.initFromBinary(inputStream); + this.objectOrientation.initFromBinary(inputStream); + this.objectAppearance = inputStream.readFloat64(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.pad2 = inputStream.readUInt(); + }; + + dis.PointObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectLocation.encodeToBinary(outputStream); + this.objectOrientation.encodeToBinary(outputStream); + outputStream.writeFloat64(this.objectAppearance); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + outputStream.writeUInt(this.pad2); + }; +}; // end of class + + // node.js module support +exports.PointObjectStatePdu = dis.PointObjectStatePdu; + +// End of PointObjectStatePdu class + +/** + * Data about a propulsion system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PropulsionSystemData = function() +{ + /** powerSetting */ + this.powerSetting = 0; + + /** engine RPMs */ + this.engineRpm = 0; + + dis.PropulsionSystemData.prototype.initFromBinary = function(inputStream) + { + this.powerSetting = inputStream.readFloat32(); + this.engineRpm = inputStream.readFloat32(); + }; + + dis.PropulsionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.powerSetting); + outputStream.writeFloat32(this.engineRpm); + }; +}; // end of class + + // node.js module support +exports.PropulsionSystemData = dis.PropulsionSystemData; + +// End of PropulsionSystemData class + +/** + * Section 5.3.8. Abstract superclass for radio communications PDUs. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioCommunicationsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.RadioCommunicationsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.RadioCommunicationsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.RadioCommunicationsFamilyPdu = dis.RadioCommunicationsFamilyPdu; + +// End of RadioCommunicationsFamilyPdu class + +/** + * Section 5.2.25. Identifies the type of radio + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioEntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** specific info based on subcategory field */ + this.nomenclatureVersion = 0; + + this.nomenclature = 0; + + dis.RadioEntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.nomenclatureVersion = inputStream.readUByte(); + this.nomenclature = inputStream.readUShort(); + }; + + dis.RadioEntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.nomenclatureVersion); + outputStream.writeUShort(this.nomenclature); + }; +}; // end of class + + // node.js module support +exports.RadioEntityType = dis.RadioEntityType; + +// End of RadioEntityType class + +/** + * Section 5.3.8.3. Communication of a receiver state. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ReceiverPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 27; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.receiverState = 0; + + /** padding */ + this.padding1 = 0; + + /** received power */ + this.receivedPower = 0; + + /** ID of transmitter */ + this.transmitterEntityId = new dis.EntityID(); + + /** ID of transmitting radio */ + this.transmitterRadioId = 0; + + dis.ReceiverPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.receiverState = inputStream.readUShort(); + this.padding1 = inputStream.readUShort(); + this.receivedPower = inputStream.readFloat32(); + this.transmitterEntityId.initFromBinary(inputStream); + this.transmitterRadioId = inputStream.readUShort(); + }; + + dis.ReceiverPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.receiverState); + outputStream.writeUShort(this.padding1); + outputStream.writeFloat32(this.receivedPower); + this.transmitterEntityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.transmitterRadioId); + }; +}; // end of class + + // node.js module support +exports.ReceiverPdu = dis.ReceiverPdu; + +// End of ReceiverPdu class + +/** + * Section 5.3.12.13: A request for one or more records of data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 65; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** event type */ + this.eventType = 0; + + /** time */ + this.time = 0; + + /** numberOfRecords */ + this.numberOfRecords = 0; + + /** record IDs */ + this.recordIDs = new Array(); + + dis.RecordQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.eventType = inputStream.readUShort(); + this.time = inputStream.readUInt(); + this.numberOfRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecords; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.recordIDs.push(anX); + } + + }; + + dis.RecordQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.time); + outputStream.writeUInt(this.numberOfRecords); + for(var idx = 0; idx < this.recordIDs.length; idx++) + { + recordIDs[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.RecordQueryReliablePdu = dis.RecordQueryReliablePdu; + +// End of RecordQueryReliablePdu class + +/** + * Record sets, used in transfer control request PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordSet = function() +{ + /** record ID */ + this.recordID = 0; + + /** record set serial number */ + this.recordSetSerialNumber = 0; + + /** record length */ + this.recordLength = 0; + + /** record count */ + this.recordCount = 0; + + /** ^^^This is wrong--variable sized data records */ + this.recordValues = 0; + + /** ^^^This is wrong--variable sized padding */ + this.pad4 = 0; + + dis.RecordSet.prototype.initFromBinary = function(inputStream) + { + this.recordID = inputStream.readUInt(); + this.recordSetSerialNumber = inputStream.readUInt(); + this.recordLength = inputStream.readUShort(); + this.recordCount = inputStream.readUShort(); + this.recordValues = inputStream.readUShort(); + this.pad4 = inputStream.readUByte(); + }; + + dis.RecordSet.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.recordID); + outputStream.writeUInt(this.recordSetSerialNumber); + outputStream.writeUShort(this.recordLength); + outputStream.writeUShort(this.recordCount); + outputStream.writeUShort(this.recordValues); + outputStream.writeUByte(this.pad4); + }; +}; // end of class + + // node.js module support +exports.RecordSet = dis.RecordSet; + +// End of RecordSet class + +/** + * 5.2.56. Purpose for joinging two entities + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Relationship = function() +{ + /** Nature of join */ + this.nature = 0; + + /** position of join */ + this.position = 0; + + dis.Relationship.prototype.initFromBinary = function(inputStream) + { + this.nature = inputStream.readUShort(); + this.position = inputStream.readUShort(); + }; + + dis.Relationship.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.nature); + outputStream.writeUShort(this.position); + }; +}; // end of class + + // node.js module support +exports.Relationship = dis.Relationship; + +// End of Relationship class + +/** + * Section 5.3.6.2. Remove an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 12; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.RemoveEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityPdu = dis.RemoveEntityPdu; + +// End of RemoveEntityPdu class + +/** + * Section 5.3.12.2: Removal of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 52; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.RemoveEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityReliablePdu = dis.RemoveEntityReliablePdu; + +// End of RemoveEntityReliablePdu class + +/** + * Section 5.2.5.5. Repair is complete. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairCompletePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 9; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Enumeration for type of repair */ + this.repair = 0; + + /** padding, number prevents conflict with superclass ivar name */ + this.padding2 = 0; + + dis.RepairCompletePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repair = inputStream.readUShort(); + this.padding2 = inputStream.readShort(); + }; + + dis.RepairCompletePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.repair); + outputStream.writeShort(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairCompletePdu = dis.RepairCompletePdu; + +// End of RepairCompletePdu class + +/** + * Section 5.2.5.6. Sent after repair complete PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 10; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Result of repair operation */ + this.repairResult = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + dis.RepairResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repairResult = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + }; + + dis.RepairResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.repairResult); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairResponsePdu = dis.RepairResponsePdu; + +// End of RepairResponsePdu class + +/** + * Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyCancelPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 8; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + dis.ResupplyCancelPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + }; + + dis.ResupplyCancelPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.ResupplyCancelPdu = dis.ResupplyCancelPdu; + +// End of ResupplyCancelPdu class + +/** + * Section 5.3.5.2. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyOfferPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 6; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyOfferPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyOfferPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyOfferPdu = dis.ResupplyOfferPdu; + +// End of ResupplyOfferPdu class + +/** + * Section 5.3.5.3. Receipt of supplies is communiated. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyReceivedPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 7; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyReceivedPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyReceivedPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyReceivedPdu = dis.ResupplyReceivedPdu; + +// End of ResupplyReceivedPdu class + +/** + * Section 5.3.7.5. SEES PDU, supplemental emissions entity state information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SeesPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 30; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Originating entity ID */ + this.orginatingEntityID = new dis.EntityID(); + + /** IR Signature representation index */ + this.infraredSignatureRepresentationIndex = 0; + + /** acoustic Signature representation index */ + this.acousticSignatureRepresentationIndex = 0; + + /** radar cross section representation index */ + this.radarCrossSectionSignatureRepresentationIndex = 0; + + /** how many propulsion systems */ + this.numberOfPropulsionSystems = 0; + + /** how many vectoring nozzle systems */ + this.numberOfVectoringNozzleSystems = 0; + + /** variable length list of propulsion system data */ + this.propulsionSystemData = new Array(); + + /** variable length list of vectoring system data */ + this.vectoringSystemData = new Array(); + + dis.SeesPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.infraredSignatureRepresentationIndex = inputStream.readUShort(); + this.acousticSignatureRepresentationIndex = inputStream.readUShort(); + this.radarCrossSectionSignatureRepresentationIndex = inputStream.readUShort(); + this.numberOfPropulsionSystems = inputStream.readUShort(); + this.numberOfVectoringNozzleSystems = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPropulsionSystems; idx++) + { + var anX = new dis.PropulsionSystemData(); + anX.initFromBinary(inputStream); + this.propulsionSystemData.push(anX); + } + + for(var idx = 0; idx < this.numberOfVectoringNozzleSystems; idx++) + { + var anX = new dis.VectoringNozzleSystemData(); + anX.initFromBinary(inputStream); + this.vectoringSystemData.push(anX); + } + + }; + + dis.SeesPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.infraredSignatureRepresentationIndex); + outputStream.writeUShort(this.acousticSignatureRepresentationIndex); + outputStream.writeUShort(this.radarCrossSectionSignatureRepresentationIndex); + outputStream.writeUShort(this.numberOfPropulsionSystems); + outputStream.writeUShort(this.numberOfVectoringNozzleSystems); + for(var idx = 0; idx < this.propulsionSystemData.length; idx++) + { + propulsionSystemData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.vectoringSystemData.length; idx++) + { + vectoringSystemData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SeesPdu = dis.SeesPdu; + +// End of SeesPdu class + +/** + * Section 5.3.5.1. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ServiceRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 5; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is requesting service */ + this.requestingEntityID = new dis.EntityID(); + + /** Entity that is providing the service */ + this.servicingEntityID = new dis.EntityID(); + + /** type of service requested */ + this.serviceTypeRequested = 0; + + /** How many requested */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.serviceRequestPadding = 0; + + this.supplies = new Array(); + + dis.ServiceRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.requestingEntityID.initFromBinary(inputStream); + this.servicingEntityID.initFromBinary(inputStream); + this.serviceTypeRequested = inputStream.readUByte(); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.serviceRequestPadding = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ServiceRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.requestingEntityID.encodeToBinary(outputStream); + this.servicingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.serviceTypeRequested); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.serviceRequestPadding); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ServiceRequestPdu = dis.ServiceRequestPdu; + +// End of ServiceRequestPdu class + +/** + * Section 5.3.6.9. Change state information with the data contained in this. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 19; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.SetDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.SetDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataPdu = dis.SetDataPdu; + +// End of SetDataPdu class + +/** + * Section 5.3.12.9: initializing or chaning internal state information, reliable. Needs manual intervention to fix padding on variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 59; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.SetDataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.SetDataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataReliablePdu = dis.SetDataReliablePdu; + +// End of SetDataReliablePdu class + +/** + * Section 5.3.12.14: Initializing or changing internal parameter info. Needs manual intervention to fix padding in recrod set PDUs. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetRecordReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 64; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Number of record sets in list */ + this.numberOfRecordSets = 0; + + /** record sets */ + this.recordSets = new Array(); + + dis.SetRecordReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfRecordSets = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.SetRecordReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetRecordReliablePdu = dis.SetRecordReliablePdu; + +// End of SetRecordReliablePdu class + +/** + * Shaft RPMs, used in underwater acoustic clacluations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ShaftRPMs = function() +{ + /** Current shaft RPMs */ + this.currentShaftRPMs = 0; + + /** ordered shaft rpms */ + this.orderedShaftRPMs = 0; + + /** rate of change of shaft RPMs */ + this.shaftRPMRateOfChange = 0; + + dis.ShaftRPMs.prototype.initFromBinary = function(inputStream) + { + this.currentShaftRPMs = inputStream.readShort(); + this.orderedShaftRPMs = inputStream.readShort(); + this.shaftRPMRateOfChange = inputStream.readFloat32(); + }; + + dis.ShaftRPMs.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeShort(this.currentShaftRPMs); + outputStream.writeShort(this.orderedShaftRPMs); + outputStream.writeFloat32(this.shaftRPMRateOfChange); + }; +}; // end of class + + // node.js module support +exports.ShaftRPMs = dis.ShaftRPMs; + +// End of ShaftRPMs class + +/** + * Section 5.3.8.2. Detailed information about a radio transmitter. This PDU requires manually written code to complete. The encodingScheme field can be used in multiple ways, which requires hand-written code to finish. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 26; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.encodingScheme = 0; + + /** tdl type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** length of data, in bits */ + this.dataLength = 0; + + /** number of samples. If the PDU contains encoded audio, this should be zero. */ + this.samples = 0; + + /** list of eight bit values. Must be padded to fall on a 32 bit boundary. */ + this.data = new Array(); + + dis.SignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.SignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SignalPdu = dis.SignalPdu; + +// End of SignalPdu class + +/** + * Section 5.2.14.1. A Simulation Address record shall consist of the Site Identification number and the Application Identification number. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationAddress = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + dis.SimulationAddress.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + }; + + dis.SimulationAddress.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + }; +}; // end of class + + // node.js module support +exports.SimulationAddress = dis.SimulationAddress; + +// End of SimulationAddress class + +/** + * Section 5.3.6. Abstract superclass for PDUs relating to the simulation itself. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementFamilyPdu = dis.SimulationManagementFamilyPdu; + +// End of SimulationManagementFamilyPdu class + +/** + * Section 5.3.12: Abstract superclass for reliable simulation management PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementWithReliabilityFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementWithReliabilityFamilyPdu = dis.SimulationManagementWithReliabilityFamilyPdu; + +// End of SimulationManagementWithReliabilityFamilyPdu class + +/** + * 48 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SixByteChunk = function() +{ + /** six bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0); + + dis.SixByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 6; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.SixByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 6; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.SixByteChunk = dis.SixByteChunk; + +// End of SixByteChunk class + +/** + * Section 5.2.4.3. Used when the antenna pattern type in the transmitter pdu is of value 2. Specified the direction and radiation pattern from a radio transmitter's antenna. NOTE: this class must be hand-coded to clean up some implementation details. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SphericalHarmonicAntennaPattern = function() +{ + this.harmonicOrder = 0; + + dis.SphericalHarmonicAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.harmonicOrder = inputStream.readByte(); + }; + + dis.SphericalHarmonicAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeByte(this.harmonicOrder); + }; +}; // end of class + + // node.js module support +exports.SphericalHarmonicAntennaPattern = dis.SphericalHarmonicAntennaPattern; + +// End of SphericalHarmonicAntennaPattern class + +/** + * Section 5.2.6.3. Start or resume an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 13; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall start or resume */ + this.realWorldTime = new dis.ClockTime(); + + /** Simulation clock time at which the simulation shall start or resume */ + this.simulationTime = new dis.ClockTime(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.StartResumePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumePdu = dis.StartResumePdu; + +// End of StartResumePdu class + +/** + * Section 5.3.12.3: Start resume simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 53; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** time in simulation for the simulation to resume */ + this.simulationTime = new dis.ClockTime(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StartResumeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumeReliablePdu = dis.StartResumeReliablePdu; + +// End of StartResumeReliablePdu class + +/** + * Section 5.2.3.4. Stop or freeze an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 14; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall stop or freeze */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason the simulation was stopped or frozen */ + this.reason = 0; + + /** Internal behavior of the simulation and its appearance while frozento the other participants */ + this.frozenBehavior = 0; + + /** padding */ + this.padding1 = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.StopFreezePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeShort(this.padding1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezePdu = dis.StopFreezePdu; + +// End of StopFreezePdu class + +/** + * Section 5.3.12.4: Stop freeze simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 54; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason for stopping/freezing simulation */ + this.reason = 0; + + /** internal behvior of the simulation while frozen */ + this.frozenBehavior = 0; + + /** reliablity level */ + this.requiredReliablityService = 0; + + /** padding */ + this.pad1 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StopFreezeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.requiredReliablityService = inputStream.readUByte(); + this.pad1 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeUByte(this.requiredReliablityService); + outputStream.writeUByte(this.pad1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezeReliablePdu = dis.StopFreezeReliablePdu; + +// End of StopFreezeReliablePdu class + +/** + * Section 5.2.30. A supply, and the amount of that supply. Similar to an entity kind but with the addition of a quantity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SupplyQuantity = function() +{ + /** Type of supply */ + this.supplyType = new dis.EntityType(); + + /** quantity to be supplied */ + this.quantity = 0; + + dis.SupplyQuantity.prototype.initFromBinary = function(inputStream) + { + this.supplyType.initFromBinary(inputStream); + this.quantity = inputStream.readUByte(); + }; + + dis.SupplyQuantity.prototype.encodeToBinary = function(outputStream) + { + this.supplyType.encodeToBinary(outputStream); + outputStream.writeUByte(this.quantity); + }; +}; // end of class + + // node.js module support +exports.SupplyQuantity = dis.SupplyQuantity; + +// End of SupplyQuantity class + +/** + * Section 5.3.11: Abstract superclass for synthetic environment PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SyntheticEnvironmentFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.SyntheticEnvironmentFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.SyntheticEnvironmentFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.SyntheticEnvironmentFamilyPdu = dis.SyntheticEnvironmentFamilyPdu; + +// End of SyntheticEnvironmentFamilyPdu class + +/** + * 5.2.58. Used in IFF ATC PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SystemID = function() +{ + /** System Type */ + this.systemType = 0; + + /** System name, an enumeration */ + this.systemName = 0; + + /** System mode */ + this.systemMode = 0; + + /** Change Options */ + this.changeOptions = 0; + + dis.SystemID.prototype.initFromBinary = function(inputStream) + { + this.systemType = inputStream.readUShort(); + this.systemName = inputStream.readUShort(); + this.systemMode = inputStream.readUByte(); + this.changeOptions = inputStream.readUByte(); + }; + + dis.SystemID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.systemType); + outputStream.writeUShort(this.systemName); + outputStream.writeUByte(this.systemMode); + outputStream.writeUByte(this.changeOptions); + }; +}; // end of class + + // node.js module support +exports.SystemID = dis.SystemID; + +// End of SystemID class + +/** + * One track/jam target + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TrackJamTarget = function() +{ + /** track/jam target */ + this.trackJam = new dis.EntityID(); + + /** Emitter ID */ + this.emitterID = 0; + + /** beam ID */ + this.beamID = 0; + + dis.TrackJamTarget.prototype.initFromBinary = function(inputStream) + { + this.trackJam.initFromBinary(inputStream); + this.emitterID = inputStream.readUByte(); + this.beamID = inputStream.readUByte(); + }; + + dis.TrackJamTarget.prototype.encodeToBinary = function(outputStream) + { + this.trackJam.encodeToBinary(outputStream); + outputStream.writeUByte(this.emitterID); + outputStream.writeUByte(this.beamID); + }; +}; // end of class + + // node.js module support +exports.TrackJamTarget = dis.TrackJamTarget; + +// End of TrackJamTarget class + +/** + * Section 5.3.9.3 Information initiating the dyanic allocation and control of simulation entities between two simulation applications. Requires manual cleanup. The padding between record sets is variable. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransferControlRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 35; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating request */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving request */ + this.recevingEntityID = new dis.EntityID(); + + /** ID ofrequest */ + this.requestID = 0; + + /** required level of reliabliity service. */ + this.requiredReliabilityService = 0; + + /** type of transfer desired */ + this.tranferType = 0; + + /** The entity for which control is being requested to transfer */ + this.transferEntityID = new dis.EntityID(); + + /** number of record sets to transfer */ + this.numberOfRecordSets = 0; + + /** ^^^This is wrong--the RecordSet class needs more work */ + this.recordSets = new Array(); + + dis.TransferControlRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.recevingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.tranferType = inputStream.readUByte(); + this.transferEntityID.initFromBinary(inputStream); + this.numberOfRecordSets = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.TransferControlRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.recevingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUByte(this.tranferType); + this.transferEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransferControlRequestPdu = dis.TransferControlRequestPdu; + +// End of TransferControlRequestPdu class + +/** + * Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete, since the modulation parameters are of variable length. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransmitterPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 25; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** linear accelleration of entity */ + this.radioEntityType = new dis.RadioEntityType(); + + /** transmit state */ + this.transmitState = 0; + + /** input source */ + this.inputSource = 0; + + /** padding */ + this.padding1 = 0; + + /** Location of antenna */ + this.antennaLocation = new dis.Vector3Double(); + + /** relative location of antenna, in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + /** antenna pattern type */ + this.antennaPatternType = 0; + + /** atenna pattern length */ + this.antennaPatternCount = 0; + + /** frequency */ + this.frequency = 0; + + /** transmit frequency Bandwidth */ + this.transmitFrequencyBandwidth = 0; + + /** transmission power */ + this.power = 0; + + /** modulation */ + this.modulationType = new dis.ModulationType(); + + /** crypto system enumeration */ + this.cryptoSystem = 0; + + /** crypto system key identifer */ + this.cryptoKeyId = 0; + + /** how many modulation parameters we have */ + this.modulationParameterCount = 0; + + /** padding2 */ + this.padding2 = 0; + + /** padding3 */ + this.padding3 = 0; + + /** variable length list of modulation parameters */ + this.modulationParametersList = new Array(); + + /** variable length list of antenna pattern records */ + this.antennaPatternList = new Array(); + + dis.TransmitterPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.radioEntityType.initFromBinary(inputStream); + this.transmitState = inputStream.readUByte(); + this.inputSource = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + this.antennaPatternType = inputStream.readUShort(); + this.antennaPatternCount = inputStream.readUShort(); + this.frequency = inputStream.readLong(); + this.transmitFrequencyBandwidth = inputStream.readFloat32(); + this.power = inputStream.readFloat32(); + this.modulationType.initFromBinary(inputStream); + this.cryptoSystem = inputStream.readUShort(); + this.cryptoKeyId = inputStream.readUShort(); + this.modulationParameterCount = inputStream.readUByte(); + this.padding2 = inputStream.readUShort(); + this.padding3 = inputStream.readUByte(); + for(var idx = 0; idx < this.modulationParameterCount; idx++) + { + var anX = new dis.ModulationType(); + anX.initFromBinary(inputStream); + this.modulationParametersList.push(anX); + } + + for(var idx = 0; idx < this.antennaPatternCount; idx++) + { + var anX = new dis.BeamAntennaPattern(); + anX.initFromBinary(inputStream); + this.antennaPatternList.push(anX); + } + + }; + + dis.TransmitterPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + this.radioEntityType.encodeToBinary(outputStream); + outputStream.writeUByte(this.transmitState); + outputStream.writeUByte(this.inputSource); + outputStream.writeUShort(this.padding1); + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + outputStream.writeUShort(this.antennaPatternType); + outputStream.writeUShort(this.antennaPatternCount); + outputStream.writeLong(this.frequency); + outputStream.writeFloat32(this.transmitFrequencyBandwidth); + outputStream.writeFloat32(this.power); + this.modulationType.encodeToBinary(outputStream); + outputStream.writeUShort(this.cryptoSystem); + outputStream.writeUShort(this.cryptoKeyId); + outputStream.writeUByte(this.modulationParameterCount); + outputStream.writeUShort(this.padding2); + outputStream.writeUByte(this.padding3); + for(var idx = 0; idx < this.modulationParametersList.length; idx++) + { + modulationParametersList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.antennaPatternList.length; idx++) + { + antennaPatternList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransmitterPdu = dis.TransmitterPdu; + +// End of TransmitterPdu class + +/** + * 16 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TwoByteChunk = function() +{ + /** two bytes of arbitrary data */ + this.otherParameters = new Array(0, 0); + + dis.TwoByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 2; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.TwoByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 2; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.TwoByteChunk = dis.TwoByteChunk; + +// End of TwoByteChunk class + +/** + * Section 5.3.7.3. Information about underwater acoustic emmissions. This requires manual cleanup. The beam data records should ALL be a the finish, rather than attached to each emitter system. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UaPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 29; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emission */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU */ + this.stateChangeIndicator = 0; + + /** padding */ + this.pad = 0; + + /** This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. */ + this.passiveParameterIndex = 0; + + /** This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. */ + this.propulsionPlantConfiguration = 0; + + /** This field shall represent the number of shafts on a platform */ + this.numberOfShafts = 0; + + /** This field shall indicate the number of APAs described in the current UA PDU */ + this.numberOfAPAs = 0; + + /** This field shall specify the number of UA emitter systems being described in the current UA PDU */ + this.numberOfUAEmitterSystems = 0; + + /** shaft RPM values */ + this.shaftRPMs = new Array(); + + /** apaData */ + this.apaData = new Array(); + + this.emitterSystems = new Array(); + + dis.UaPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateChangeIndicator = inputStream.readByte(); + this.pad = inputStream.readByte(); + this.passiveParameterIndex = inputStream.readUShort(); + this.propulsionPlantConfiguration = inputStream.readUByte(); + this.numberOfShafts = inputStream.readUByte(); + this.numberOfAPAs = inputStream.readUByte(); + this.numberOfUAEmitterSystems = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfShafts; idx++) + { + var anX = new dis.ShaftRPMs(); + anX.initFromBinary(inputStream); + this.shaftRPMs.push(anX); + } + + for(var idx = 0; idx < this.numberOfAPAs; idx++) + { + var anX = new dis.ApaData(); + anX.initFromBinary(inputStream); + this.apaData.push(anX); + } + + for(var idx = 0; idx < this.numberOfUAEmitterSystems; idx++) + { + var anX = new dis.AcousticEmitterSystemData(); + anX.initFromBinary(inputStream); + this.emitterSystems.push(anX); + } + + }; + + dis.UaPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeByte(this.stateChangeIndicator); + outputStream.writeByte(this.pad); + outputStream.writeUShort(this.passiveParameterIndex); + outputStream.writeUByte(this.propulsionPlantConfiguration); + outputStream.writeUByte(this.numberOfShafts); + outputStream.writeUByte(this.numberOfAPAs); + outputStream.writeUByte(this.numberOfUAEmitterSystems); + for(var idx = 0; idx < this.shaftRPMs.length; idx++) + { + shaftRPMs[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.apaData.length; idx++) + { + apaData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.emitterSystems.length; idx++) + { + emitterSystems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.UaPdu = dis.UaPdu; + +// End of UaPdu class + +/** + * Wrapper for an unsigned 32 bit integer + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UnsignedIntegerWrapper = function() +{ + /** name can't be too accurate or the generated source code will have reserved word problems */ + this.wrapper = 0; + + dis.UnsignedIntegerWrapper.prototype.initFromBinary = function(inputStream) + { + this.wrapper = inputStream.readUInt(); + }; + + dis.UnsignedIntegerWrapper.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.wrapper); + }; +}; // end of class + + // node.js module support +exports.UnsignedIntegerWrapper = dis.UnsignedIntegerWrapper; + +// End of UnsignedIntegerWrapper class + +/** + * Section 5.2.32. Variable Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VariableDatum = function() +{ + /** ID of the variable datum */ + this.variableDatumID = 0; + + /** length of the variable datums, in bits. Note that this is not programmatically tied to the size of the variableData. The variable data field may be 64 bits long but only 16 bits of it could actually be used. */ + this.variableDatumLength = 0; + + /** data can be any length, but must increase in 8 byte quanta. This requires some postprocessing patches. Note that setting the data allocates a new internal array to account for the possibly increased size. The default initial size is 64 bits. */ + this.variableData = new Array(); + + dis.VariableDatum.prototype.initFromBinary = function(inputStream) + { + this.variableDatumID = inputStream.readUInt(); + this.variableDatumLength = inputStream.readUInt(); + for(var idx = 0; idx < this.variableDatumLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.variableData.push(anX); + } + + }; + + dis.VariableDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.variableDatumID); + outputStream.writeUInt(this.variableDatumLength); + for(var idx = 0; idx < this.variableData.length; idx++) + { + variableData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.VariableDatum = dis.VariableDatum; + +// End of VariableDatum class + +/** + * Section 5.3.34. Three double precision floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Double = function() +{ + /** X value */ + this.x = 0; + + /** Y value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Double.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat64(); + this.y = inputStream.readFloat64(); + this.z = inputStream.readFloat64(); + }; + + dis.Vector3Double.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat64(this.x); + outputStream.writeFloat64(this.y); + outputStream.writeFloat64(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Double = dis.Vector3Double; + +// End of Vector3Double class + +/** + * Section 5.2.33. Three floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Float = function() +{ + /** X value */ + this.x = 0; + + /** y Value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Float.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.Vector3Float.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Float = dis.Vector3Float; + +// End of Vector3Float class + +/** + * Data about a vectoring nozzle system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VectoringNozzleSystemData = function() +{ + /** horizontal deflection angle */ + this.horizontalDeflectionAngle = 0; + + /** vertical deflection angle */ + this.verticalDeflectionAngle = 0; + + dis.VectoringNozzleSystemData.prototype.initFromBinary = function(inputStream) + { + this.horizontalDeflectionAngle = inputStream.readFloat32(); + this.verticalDeflectionAngle = inputStream.readFloat32(); + }; + + dis.VectoringNozzleSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.horizontalDeflectionAngle); + outputStream.writeFloat32(this.verticalDeflectionAngle); + }; +}; // end of class + + // node.js module support +exports.VectoringNozzleSystemData = dis.VectoringNozzleSystemData; + +// End of VectoringNozzleSystemData class + +/** + * Section 5.3.4. abstract superclass for fire and detonation pdus that have shared information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.WarfareFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + dis.WarfareFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + }; + + dis.WarfareFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.WarfareFamilyPdu = dis.WarfareFamilyPdu; + +// End of WarfareFamilyPdu class + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/googleMaps.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/googleMaps.html new file mode 100644 index 0000000000000000000000000000000000000000..586fe95edf039700be162d71083dbd3e5e037cf4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/googleMaps.html @@ -0,0 +1,328 @@ + +<!-- +Note that if you want to use this web page from clients other than the +one running on the same host as the web browser, you MUST change the +url the websocket connects to. + +A demo that uses google map's Javascript api and web sockets. We receive +updates in IEEE 1278 DIS binary format, and place icons on the map for each +entity's location. The icons are clickable for more info. Typically the server +will be forwarding information, including from the server-local network, for such +information as may be being put out by VBS2 or the like. + +Does the conversion from DIS global (geocentric/earth-centered, earth-fixed) +to lat/lon/alt. +--> +<!DOCTYPE html> +<html> + <head> + <title>Google Maps</title> + <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> + <meta name="viewport" content="initial-scale=1.0, user-scalable=no"/> + + <style type="text/css"> + html {height:100%} + body { height:100%; margin:0; padding:0 } + #map-canvas{height:100% } + </style> + + + <!-- Binary DIS implementation, also coordinate system conversion utilities --> + <script type="text/javascript" src="dis.js"></script> + + <!-- Note: this is using an Google Maps API key linked to me, DMcG. For serious use, go to --> + <!-- https://code.google.com/apis/console and get your own api key. Using this key is fine for demo purposes. --> + <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyAZihiWY3ho8hHfkhu9_6mcMSkxSvpjbTI&sensor=true"></script> + <!--script type="text/javascript" src="javascript/DisAppearance.js"></script--> + + </head> + <body> + <div id="map-canvas"></div> + + + <SCRIPT type="text/javascript"> + /** This works if you're running client and server on one host. To + * have it work with a remote server, replace localhost with the IP + * or name of the server. + */ + //var WEBSOCKET_URL="ws://192.168.60.204/ws"; + //var WEBSOCKET_URL="ws://172.20.82.141:8282"; + //var WEBSOCKET_URL="ws://172.20.152.19:8485"; + var WEBSOCKET_URL="ws://track.movesinstitute.org:80"; + var map; + var websocket; + /** A likely map location */ + var montereyLocation = new google.maps.LatLng(36.595, -121.877); + var orlandoLocation = new google.maps.LatLng(28.425, -81.47); + + /** Marker for the entity represented by this web browser's location */ + var ourMarker; + + /** current location of the device running this browser, as defined by geolocation api. + * This is the W3C geolocation position object, not the google maps object. + * coords.latitude, coords.longitude, coords.altitude are among the properties. + */ + var browserPosition; + + /** Hash table Used to keep track of all entities in the world */ + var allEntities = {}; + + /** EntityStatePdu for the entity represented by this page. This is + * periodically sent as a heartbeat, so others can find us. */ + var espdu = new dis.EntityStatePdu(); + espdu.marking.setMarking("IITSECDemo"); + //console.log(espdu.marking); + + //console.log(JSON.stringify(espdu)); + + /** Used to convert DIS earth-centered coordinates to lat/lon/alt */ + var conversion = new dis.CoordinateConversion(); + + /** benchmarking */ + var messageCount = 0; var startTime = new Date(); + + /** icon path*/ + var iconBase = '/images'; + + // Set the initialize function to run on page load + google.maps.event.addDomListener(window, 'load', initialize); + + /** + * Initialize the map and websocket + * + * @returns {undefined} + */ + function initialize() + { + + var coordinateConversion = new dis.CoordinateConversion(); + + var position = {}; + position.lat = 50.430436041848; + position.lon = 45.4806844718347; + position.alt = 16.2087463214993; + + var xyz = coordinateConversion.getXYZfromLatLonAltDegrees(position); + console.log("xyz for postion is ", xyz); + + var geocentric = {}; + geocentric.x = 2854437.74; + geocentric.y = 2902738.86; + geocentric.z = 4893439.36; + var geodetic = coordinateConversion.convertDisToLatLongInDegrees(geocentric); + console.log("geodetic for the same position: ", geodetic); + + // periodically prune entities that we haven't heard from lately + window.setInterval(prune, 60000); + + // The region of the map that's visible, and where it's centered. + var mapOptions = + { + center: montereyLocation, + zoom:14, + mapTypeId:google.maps.MapTypeId.SATELLITE + }; + map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); + + // Compatiability checks--not all web browsers support Websockets. + // note that the host portion of the URL (localhost here) MUST + // be changed to a DNS name or IP to reach it from off-host. The + // existing localhost is just there for development purposes. + if(window.WebSocket) + websocket = new WebSocket(WEBSOCKET_URL); + else if(Window.MozWebSocket) + websocket = new MozWebSocket(WEBSOCKET_URL); + else + alert("This web browser does not support web sockets"); + + // Set the format we want to use to receive binary messages + websocket.binaryType = 'arraybuffer'; + + // Attach functions to the the web socket for various events + websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; + websocket.onclose = function(evt){console.log("websocket close", evt);}; + websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + /** Handle the messages sent from the server to us here. We receive binary + * DIS from the server over the web socket. + * @param {event} evt The receive event object. Contains the binary data to decode + */ + websocket.onmessage = function(evt) + { + + console.log("Raw message: ", evt); + // Factory object for creating new PDUs from binary data + var pduFactory = new dis.PduFactory(); + + // InputStream is modeled on a Java input stream. Pass it binary data, + // and we will read through it, while input stream maintains a current + // place marker + //console.log(evt.data); + //var inputStream = new dis.InputStream(evt.data); + + var disMessage = pduFactory.createPdu(evt.data); + + //console.log(disMessage); + // You can trap the various types of PDU here, and + // probably call a specific function to handle each + // type of message. For now we return on everything but + // espdus. + + if(disMessage.pduType != 1) + return; + + // Some instrumentation for performance. This is useful if hooked + // up to an AIS feed, for example, which generates a lot of traffic. + + messageCount++; + if(messageCount % 500 === 0) + { + var timeNow = new Date(); + var difference = timeNow.getTime() - startTime.getTime(); + console.log("Packets per second for 20K packets: ", 20000 / difference * 1000); + startTime = new Date(); + //console.log(JSON.stringify(disMessage)); + } + + // Retrieve the entity ID from the DIS message, convert it to a JSON + // string, and then use that as a sleazy key into a "hash table" consisting + // of object attributes. + + var entityID = disMessage.entityID; + var eidString = JSON.stringify(entityID); + + // Convert from DIS global coordinates to latitude/longtitude + var latLonAlt = conversion.convertDisToLatLongInDegrees(disMessage.entityLocation); + + // We have an attribute on this object named the JSON text string, with a + // value of the marker data. Look that up. + var theMarker = allEntities[eidString]; + + // If it's not found, that means it's the first time we've heard of it. Create + // a new one. + + if(theMarker === undefined) + { + theMarker = {}; + var entityMarking = disMessage.marking.getMarking(); + + var contentString = "<b>Entity ID:</b>" + JSON.stringify(disMessage.entityID) + "<br>"; + contentString = contentString + "<b>Marking:</b>" + entityMarking + "<br>"; + contentString = contentString + "<b>Entity Type:</b>" + JSON.stringify(disMessage.entityType) + "<br>"; + contentString = contentString + "<b>Location:</b>" + latLonAlt.latitude + ", " +latLonAlt.longitude + ", " + latLonAlt.altitude + "<br>" + var infowindow = new google.maps.InfoWindow({content: contentString}); + + var newEntityLocation = new google.maps.LatLng(latLonAlt.latitude, latLonAlt.longitude); + // The marker (with the default icon) is automatically added + // to the map when created + var eKind = disMessage.entityType.entityKind; + if(eKind == 1){ + var marker = makeMarker('leopardSmall', newEntityLocation); + } + if(eKind == 2){ + var marker = makeMarker('hmmwvSmall', newEntityLocation); + } + + // var marker = new google.maps.Marker({ + // map:map, + // draggable:true, + // animation:google.maps.Animation.DROP, + // position: newEntityLocation, + // title:"Entity From Network", + // icon: 'tank.png' + // }); + + var iconIsBig = false; + // add a function to be called when the user clicks on the icon + google.maps.event.addListener(marker, 'click', function() + { + /*Tank picture available from + http://www.tanks-encyclopedia.com/coldwar/West_Germany/Leopard-2/Leopard-2A4M_CAN.png + */ + + if(eKind == 1){ + if (iconIsBig){ + infowindow.close(map, marker); + marker.setIcon('leopardSmall.png'); + iconIsBig=false; + }else { + infowindow.open(map,marker); + marker.setIcon('leopardBig.png'); + iconIsBig=true; + } + } + + /*HMMWV picture available from: + https://cdn.pixabay.com/photo/2016/03/31/18/22/army-1294302_960_720.png + */ + + if(eKind == 2){ + if (iconIsBig){ + infowindow.close(map, marker); + marker.setIcon('hmmwvSmall.png'); + iconIsBig=false; + }else { + infowindow.open(map,marker); + marker.setIcon('hmmwvBig.png'); + iconIsBig=true; + } + } + }); + + theMarker.marker = marker; + + //console.log("new theMarker:", theMarker); + allEntities[eidString] = theMarker; + }; + + + // The marker for the entity has either just been added, or recognized as already + // existing. In either event, update it's position on the map. + // Update the marker position + theMarker.marker.setPosition(new google.maps.LatLng(latLonAlt.latitude, latLonAlt.longitude) ); + theMarker.lastEspdu = disMessage; + theMarker.lastHeardFrom = new Date(); + + + }; // end of onmessage + + } + + /** + * Removes icons from the map if we haven't heard from in some amount of time + */ + function prune() + { + var TIMEOUT = 120000; // 2 min + var now = new Date(); + + for (var anEntity in allEntities) + { + var entityInfo = allEntities[anEntity]; + if(now.getTime() - entityInfo.lastHeardFrom.getTime() > TIMEOUT) + { + var markerInfo = allEntities[anEntity]; + markerInfo.marker.setMap(null); + delete allEntities[anEntity]; + } + } + } + + function makeMarker(imageName,position){ + var marker = new google.maps.Marker({ + map:map, + draggable:true, + animation:google.maps.Animation.DROP, + position: position, + title:"Entity From Network", + icon: imageName +'.png' + }); + return marker; + } + + + + + </SCRIPT> + </body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwv.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwv.png new file mode 100644 index 0000000000000000000000000000000000000000..047dc4b097c018a17541568549fdb9ab1c43ae34 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwv.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvBig.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvBig.png new file mode 100644 index 0000000000000000000000000000000000000000..d37531931921484ef01106217088105d27305e1e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvBig.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvSmall.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvSmall.png new file mode 100644 index 0000000000000000000000000000000000000000..97e6b00aea356c096e0d4306e8e0dcd5002d3d9b Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/hmmwvSmall.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/T-72-sideskirts.jpg b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/T-72-sideskirts.jpg new file mode 100644 index 0000000000000000000000000000000000000000..1e751c86d36862259baf8845cfbaee96a1e1681f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/T-72-sideskirts.jpg differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/russian-tank.jpg b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/russian-tank.jpg new file mode 100644 index 0000000000000000000000000000000000000000..66c9bc900ed2c1058dd5337a6a682b6998521cee Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/images/russian-tank.jpg differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardBig.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardBig.png new file mode 100644 index 0000000000000000000000000000000000000000..908ff1573d6ea904c62cad8b0055dfde47024508 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardBig.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardSmall.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardSmall.png new file mode 100644 index 0000000000000000000000000000000000000000..b2480c8c8bdb5ffa3085716a15a057d785378c43 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/leopardSmall.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/russian-tank.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/russian-tank.png new file mode 100644 index 0000000000000000000000000000000000000000..686328301422a312f5000bfd882afa0f9d7a4316 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/russian-tank.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/dis.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/dis.js new file mode 100644 index 0000000000000000000000000000000000000000..83d0e716f4d5e1ab8ff391d6d4a73589abd2474e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/dis.js @@ -0,0 +1,13979 @@ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.CoordinateConversion = function() + { + + this.RADIANS_TO_DEGREES = 180.0/Math.PI; + this.DEGREES_TO_RADIANS = Math.PI/180.0; + + this.a = 6378137.0; //semi major axis (WGS 84) + this.b = 6356752.3142; //semi minor axis (WGS 84) + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.CoordinateConversion.prototype.convertDisToLatLongInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared; //second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + var a = 6378137.0; // shorter variable names + var b = 6356752.3142; + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a * a) / Math.sqrt(((a * a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var result = {latitude:answer[0] * this.RADIANS_TO_DEGREES, longitude:answer[1] * this.RADIANS_TO_DEGREES, altitude:answer[2]}; + return result; + + }; + + /** + * Converts lat long and geodetic height (elevation) into DIS XYZ + * This algorithm also uses the WGS84 ellipsoid, though you can change the values + * of a and b for a different ellipsoid. Adapted from Military Handbook 600008 + * @param latLonAlt {lat: lon: alt:} in degrees and meters + * @return {x: y: z:} in meters + */ + dis.CoordinateConversion.prototype.getXYZfromLatLonAltDegrees = function(latLonAlt) + { + var latitudeRadians = latLonAlt.lat * this.DEGREES_TO_RADIANS; + var longtitudeRadians = latLonAlt.lon * this.DEGREES_TO_RADIANS; + + var cosLat = Math.cos(latitudeRadians); + var sinLat = Math.sin(latitudeRadians); + + + var rSubN = (this.a * this.a) / Math.sqrt(((this.a * this.a) * (cosLat * cosLat) + ((this.b * this.b) * (sinLat*sinLat)))); + + var X = (rSubN + latLonAlt.alt) * cosLat * Math.cos(longtitudeRadians); + var Y = (rSubN + latLonAlt.alt) * cosLat * Math.sin(longtitudeRadians); + var Z = ((((this.b * this.b) / (this.a * this.a)) * rSubN) + latLonAlt.alt) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + }; + + exports.CoordinateConversion = dis.CoordinateConversion; +/** + * Obsolete--the code generation now includes methods for accessing bit + * fields such as this. Remains only for backward compatiblity, and I doubt + * anyone is using it. + * + * Some code to extract the entity apperance bit fields.<p> + * + * The entityAppearance field in the espdu is a 32 bit integer. To save + * space, several different fields are contained within it. + * Specifically: + * + * Name bit position Purpose + * ---- ------------ -------- + * Paint 0 0 = uniform color, 1=camo + * Mobility 1 0 = no mobility kill, 1 = mobility kill + * Fire Power 2 0 = no firepower kill, 1 = firepower kill + * Damage 3-4 0=no damange, 1=slight, 2=moderate, 3=destroyed + * Smoke 5-6 0=not smoking, 1=smoke plume, 2=emitting engine smoke, 3=engine smoke + smoke plume + * Trailing effects 7-8 dust cloud, 0=none, 1=small, 2=medium, 3=large + * hatch 9-11 0=NA, 1=hatch closed, 2=popped, 3=popped + person visible, 4=open, 5=open and visible + * head lights 12 0=off, 1=on + * tail light 13 0=off, 1=on + * brake lights 14 0=off, 1=on + * flaming 15 0=none, 1=flames present + * launcher 16 0=not raised, 1=raised + * camo type 17-18 0=desert, 1=winter, 2=forest + * concealed 19 0=not concealed, 1=prepared concealed position (netting, etc) + * frozen status 20 0=not frozen, 1=frozen (in simulation terms) + * power plant 22 0=power plant off 1=on + * state 23 0=active, 1=deactivated + * tent 24 0=not extended 1=extended + * ramp 25 0=not extended, 1=extended + * blackout lights 26 0=off, 1=on + * blackout brake 27 0=off, 1=on + * spot lights 28 0=off, 1=on + * interior lights 29 0=off, 1=on + * unused 30-31 + * + * Typical use: + * + * var entityAppearance = new DisAppearance(espdu.entityAppearance); + * var damage = entityAppearance.getBitfield(3, 4); + * + * This returns the "damage" bitfield in bits 3-4. + * + * var mobility = entityAppearance.getBitfield(1, 1); + * + * Returns the mobility field, 0 = no mobo kill, 1 = mobility kill + * + * @author DMcG + **/ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor. Takes the integer value extracted from the DIS Entity State Field appearance + * + * @param {type} integerValue the entity appearance from the espdu + * @returns {undefined} + */ +dis.DisAppearance = function(integerValue) +{ + this.entityAppearance = integerValue; +} + +/** + * Test code for creating the correct bitmask + * @returns {undefined} + */ +dis.DisAppearance.prototype.getTestMask = function() +{ + mask = 0; + for(var idx = 0; idx < 7; idx++) + { + mask = mask + this.bit_set(mask, idx); + } + + return mask; +}; + +/** + * + * @param {integer} startPosition + * @param {integer} finishPosition + * @returns {integer} + */ +dis.DisAppearance.prototype.getBitField = function(startPosition, finishPosition) +{ + // do some sanity checks + if(startPosition < 0 || startPosition > 31 || finishPosition < 0 || finishPosition > 31 || startPosition > finishPosition) + { + console.log("invalid start or finish for bitfield values: ", startPosition, " ", finishPosition); + return 0; + } + + // Develop the mask. Addition is equivalent to setting multiple bits. + var mask = 0; + for(var idx = startPosition; idx <= finishPosition; idx++) + { + mask = mask + this.bit_set(0, idx); + } + + // do the bitmask + var maskedValue = this.entityAppearance & mask; + // Shift bits to get the normalized value + var fieldValue = maskedValue >>> startPosition; + + return fieldValue; +}; + +/** Set the "bit" position in a number to 1 + * + * @param {integer} num the number whose bit we are setting. Typically zero. + * @param {integer} bit which bit to set + * @return {integer} the number passed in, with the "bit"th bit flipped on. + **/ +dis.DisAppearance.prototype.bit_set = function(num, bit) +{ + return num | 1<<bit; +} + +exports.DisAppearance = dis.DisAppearance; + +//var BigInteger = require('BigInteger'); + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +dis.InputStream = function(binaryData) +{ + this.dataView = new DataView(binaryData, 0); // data, byte offset + this.currentPosition = 0; // ptr to "current" position in array + + dis.InputStream.prototype.readUByte = function() + { + var data = this.dataView.getUint8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readByte = function() + { + var data = this.dataView.getInt8(this.currentPosition); + this.currentPosition = this.currentPosition + 1; + return data; + }; + + dis.InputStream.prototype.readUShort = function() + { + var data = this.dataView.getUint16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readShort = function() + { + var data = this.dataView.getInt16(this.currentPosition); + this.currentPosition = this.currentPosition + 2; + return data; + }; + + dis.InputStream.prototype.readUInt = function() + { + var data = this.dataView.getUint32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readInt = function() + { + var data = this.dataView.getInt32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + /** Read a long integer. Assumes big endian format. Uses the BigInteger package. */ + dis.InputStream.prototype.readLongInt = function() + { + var data1 = this.dataView.getInt32(this.currentPosition); + var data2 = this.dataView.getInt32(this.currentPosition + 4); + + this.currentPosition = this.currentPosition + 8; + + }; + + dis.InputStream.prototype.readFloat32 = function() + { + var data = this.dataView.getFloat32(this.currentPosition); + this.currentPosition = this.currentPosition + 4; + return data; + }; + + dis.InputStream.prototype.readFloat64 = function() + { + var data = this.dataView.getFloat64(this.currentPosition); + this.currentPosition = this.currentPosition + 8; + return data; + }; + + dis.InputStream.prototype.readLong = function() + { + console.log("Problem in dis.InputStream. Javascript cannot natively handle 64 bit ints"); + console.log("Returning 0 from read, which is almost certainly wrong"); + this.currentPosition = this.currentPosition + 8; + return 0; + }; +}; + +exports.InputStream = dis.InputStream; +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * @param binaryDataBuffer ArrayBuffer +*/ +dis.OutputStream = function(binaryDataBuffer) +{ + this.binaryData = binaryDataBuffer; + this.dataView = new DataView(this.binaryData); // data, byte offset + this.currentPosition = 0; // ptr to current position in array + + /** + * Returns a byte array trimmed to the maximum number of bytes written + * to the stream. Eg, if we initialize with a 500 byte bufer, and we + * only write 10 bytes to the output stream, this will return the first + * ten bytes of the array. + * + * @returns {ArrayBuffer} Only the data written + */ + dis.OutputStream.prototype.toByteArray = function() + { + var trimmedData = this.binaryData.slice(0, this.currentPosition); + return trimmedData; + }; + + + dis.OutputStream.prototype.writeUByte = function(userData) + { + this.dataView.setUint8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeByte = function(userData) + { + this.dataView.setInt8(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 1; + }; + + dis.OutputStream.prototype.writeUShort = function(userData) + { + this.dataView.setUint16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeShort = function(userData) + { + this.dataView.setInt16(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 2; + }; + + dis.OutputStream.prototype.writeUInt = function(userData) + { + this.dataView.setUint32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeInt = function(userData) + { + this.dataView.setInt32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat32 = function(userData) + { + this.dataView.setFloat32(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 4; + }; + + dis.OutputStream.prototype.writeFloat64 = function(userData) + { + this.dataView.setFloat64(this.currentPosition, userData); + this.currentPosition = this.currentPosition + 8; + }; + + dis.OutputStream.prototype.writeLong = function(userData) + { + console.log("Problem in dis.outputStream. Javascript cannot natively handle 64 bit ints"); + console.log("writing 0, which is almost certainly wrong"); + this.dataView.setInt32(this.currentPosition, 0); + this.dataView.setInt32(this.currentPosition + 4, 0); + this.currentPosition = this.currentPosition + 8; + }; +}; + +exports.OutputStream = dis.OutputStream; + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + + /** + * The PDU factory is responsible for decoding binary data and turning + * it into the appropriate type of PDU. + * + * The websocket will typically send the web page a IEEE 1278.1 binary + * array of data. It could be any one of dozens of PDUs. The start of + * all PDUs is the same--they have the same header. One of the fields in + * the header is the PduType, an 8 bit integer with a unqiue value for + * each type of PDU. We have to peak at that value, decide what type + * of PDU to create of the binary we have received, and then decode it. + * + * * @DMcG + */ + + dis.PduFactory = function() + { + + }; + + /** + * decode incoming binary data and + * return the correct type of PDU. + * + * @param {type} data the IEEE 1278.1 binary data + * @returns {Pdu} Returns an instance of some PDU, be it espdu, fire, detonation, etc. Exception if PduType not known. + */ + dis.PduFactory.prototype.createPdu = function(data) + { + var asUint8Array = new Uint8Array(data); + var pduType = asUint8Array[2]; + var inputStream = new dis.InputStream(data); + var newPdu = null; + + //try + //{ + switch(pduType) + { + case 1: // entity state PDU + newPdu = new dis.EntityStatePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 2: // Fire + newPdu = new dis.FirePdu(); + newPdu.initFromBinary(inputStream); + break; + + case 3: // detonation + newPdu = new dis.DetonationPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 4: // Collision + newPdu = new dis.CollisionPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 11: // Create entity + newPdu = new dis.CreateEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 12: // Remove entity + newPdu = new dis.RemoveEntityPdu(); + newPdu.initFromBinary(inputStream); + break; + + case 20: // data + newPdu = new dis.DataPdu(); + newPdu.initFromBinary(inputStream); + break; + + default: + throw "PduType: " + pduType + " Unrecognized PDUType. Add PDU in dis.PduFactory."; + } + //} + // This also picks up any errors decoding what we though was a "normal" PDU + //catch(error) + //{ + // newPdu = null; + //} + + return newPdu; + }; + + dis.PduFactory.prototype.getPdusFromBundle = function(data) + { + } + + +exports.PduFactory = dis.PduFactory; +/** + * Sets up a local tangent place (ENU) coordinate system at a given location + * and altitude, and handles conversions between geodetic, ECEF, and local + * tangent plane coordinate systems. + * + * For reference see "Conversion of Geodetic coordinates to the Local + * Tangent Plane", version 2.01, + * http://www.psas.pdx.edu/CoordinateSystem/Latitude_to_LocalTangent.pdf + * + * and "Geodetic Systems", + * http://wiki.gis.com/wiki/index.php/Geodetic_system#From_geodetic_coordinates_to_local_ENU_coordinates + * + * There's also a bunch of ancient code from older versions that someone, somewhere, + * lifted from a military handbook, originally written in C, translated to Java, + * and now translated to Javascript. + * + * Terminology: + * + * ECEF: earth centered, earth fixed coordinate system, same as DIS. Cartesian, + * origin at center of the earth, z through north pole, x out the equator and + * prime meridian, y out equator and 90 deg east. This coordinate system rotates + * with the earth, ie the x axis always points out the prime meridian and equator + * even as the earth rotates. + * + * Geodetic: latitude, longitude, altitude. + * + * WGS84: Shape of the earth, an ellipsoid roughly, with a and b the semimajor and semiminor axes + * + * ENU: East, North, Up: local coordinate system with a given geodetic origin. Tangent + * plane to the earth. + * + * All Errors mine + * + * @DMcG + * + * @param {float} lat latitude in degrees of the origin of the local tangent plane coordinate system + * @param {float} lon longitude, in degrees, of origin + * @param {float} alt altitude, in meters, of the origin of the local tangent plane coordinate system + */ + +if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** Constructor, creates an object that can do coordinate systems conversions. + * Takes a geodetic point that is the origin of a tangent plane to the surface + * of the earth. This is useful for doing local simulation work. The local + * coordinate system has postive x east, positive y north, and positive Z up, + * aka an ENU coordinate system. Methods for converting from that coordinate system + * to the DIS (ECEF) coordinate system or geotetic coordinate systems are provided. + * + * @param {type} lat latitude, in degrees, of where the local tangent plane is located + * @param {type} lon longitude, in degrees, of the origin of the local tangent plane + * @param {type} alt altitude, in meters, of the origin of the local tangent plane + * @returns {RangeCoordinates} An object that can do coordinate system conversions + */ +dis.RangeCoordinates = function(lat, lon, alt) +{ + this.RADIANS_PER_DEGREE = 2 * Math.PI / 360.0; + this.DEGREES_PER_RADIAN = 360.0 / (2* Math.PI); + + /** WGS84 semimajor axis (constant) */ + this.a = 6378137.0; + + /** WGS84 semiminor axis (constant) */ + this.b = 6356752.3142; + + /** Ellipsoidal Flatness (constant) */ + this.f = (this.a - this.b) / this.a; // Should be 3.3528107 X 10^-3 + + /** Eccentricity (constant) */ + this.e = Math.sqrt(this.f * (2 - this.f)); // Should be 8.1819191 X 10^-2 + + // The origin of the local, East-North-Up (ENU) coordinate system, in lat/lon degrees and meters. + this.ENUOrigin = {}; + this.ENUOrigin.latitude = lat; + this.ENUOrigin.longitude = lon; + this.ENUOrigin.altitude = alt; + + // Find the origin of the ENU in earth-centered, earth-fixed ECEF aka DIS coordinates + this.ENUOriginInECEF = {}; + this.ENUOriginInECEF = this.latLonAltDegreesToECEF(lat, lon, alt); +}; + + /** Determines N, the distance from a normal plane at the given + * latitude to the Z-axis running through the center of the earth. + * This is NOT the same as the distance to the center of the earth. + * + * @param {float} lambda the latitude, in radians. + * @returns {float} distance in meters from the latitude to the axis of the earth + */ + dis.RangeCoordinates.prototype.N = function(lambda) + { + //N(lambda) = a / sqrt( 1 - e^2 * sin^2(lambda) ) + var val = this.a / Math.sqrt(1- ( Math.pow(this.e, 2) * Math.pow( Math.sin(lambda), 2) ) ); + return val; + }; + + /** + * Converts a latitude, longitude, and altitude object to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {latitude:longitude:altitude:} latLonAlt The lat/lon/alt, in degrees and meters + * @returns {x, y, z} rectilienar coordinates in ECEF, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesObjectToECEF = function(latLonAlt) + { + return this.latLonAltDegreesToECEF(latLonAlt.latitude, latLonAlt.longitude, latLonAlt.altitude); + }; + + /** + * Converts a latitude, longitude, and altitude to DIS rectilinear + * coordinates, aka earth-centered, earth-fixed, rectilinear. + * + * @param {float} latitude (in radians) + * @param {float} longitude (in radians) + * @param {float} altitude (in meters) + * @returns {x, y, z} rectilienar coordinates in ECEF-r, aka DIS coordinates + */ + dis.RangeCoordinates.prototype.latLonAltRadiansToECEF = function(latitude, longitude, altitude) + { + /* + // altitude corresponds to h in the paper, lambda to latitude, phi to longitude + var x = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.cos(longitude); + var y = (altitude + this.N(latitude)) * Math.cos(latitude) * Math.sin(longitude); + var z = (altitude + (1 - Math.pow(this.e, 2) ) * this.N(latitude)) * Math.sin(longitude); + + var coordinates = {}; + coordinates.x = x; + coordinates.y = y; + coordinates.z = z; + */ + + var cosLat = Math.cos(latitude); + var sinLat = Math.sin(latitude); + + var rSubN = (this.a*this.a) / Math.sqrt(((this.a*this.a) * (cosLat*cosLat) + ((this.b*this.b) * (sinLat*sinLat)))); + + var X = (rSubN + altitude) * cosLat * Math.cos(longitude); + var Y = (rSubN + altitude) * cosLat * Math.sin(longitude); + var Z = ((((this.b*this.b) / (this.a*this.a)) * rSubN) + altitude) * sinLat; + + return {x:X, y:Y, z:Z}; + }; + + /* + * + * @param {type} latitude in degrees + * @param {type} longitude in degrees + * @param {type} altitude in meters + * @returns {x,y,z} coordinates in ECEF, in meters aka DIS global coordinates + */ + dis.RangeCoordinates.prototype.latLonAltDegreesToECEF = function(latitude, longitude, altitude) + { + return this.latLonAltRadiansToECEF(latitude * this.RADIANS_PER_DEGREE, longitude * this.RADIANS_PER_DEGREE, altitude); + }; + + /** + * Converts DIS xyz world coordinates to latitude and longitude (IN DEGREES). This algorithm may not be 100% accurate + * near the poles. Uses WGS84 , though you can change the ellipsoid constants a and b if you want to use something + * else. These formulas were obtained from Military Handbook 600008. The code itself has been + * translated from C to Java to Javascript over the years, so hold onto your hats. (This is + * copied from other sources than those listed above. Seems to work, though.) + * + * @param position {x:, y:, z:} + * @return {latitude:, longitude: altitude:} + */ + dis.RangeCoordinates.prototype.ECEFObjectToLatLongAltInDegrees = function(position) + { + var x = position.x; + var y = position.y; + var z = position.z; + + var answer = []; + answer[0] = 0.0; + answer[1] = 0.0; + answer[2] = 0.0; + var a = this.a; // semi major axis (WGS 84) + var b = this.b; //semi minor axis (WGS 84) + + var eSquared; //first eccentricity squared + var rSubN; //radius of the curvature of the prime vertical + var ePrimeSquared;//second eccentricity squared + var W = Math.sqrt((x*x + y*y)); + + eSquared = (a*a - b*b) / (a*a); + ePrimeSquared = (a*a - b*b) / (b*b); + + /** + * Get the longitude. + */ + if(x >= 0 ) + { + answer[1] = Math.atan(y/x); + } + else if(x < 0 && y >= 0) + { + answer[1] = Math.atan(y/x) + Math.PI; + } + else + { + answer[1] = Math.atan(y/x) - Math.PI; + } + /** + * Longitude calculation done. Now calculate latitude. + * NOTE: The handbook mentions using the calculated phi (latitude) value to recalculate B + * using tan B = (1-f) tan phi and then performing the entire calculation again to get more accurate values. + * However, for terrestrial applications, one iteration is accurate to .1 millimeter on the surface of the + * earth (Rapp, 1984, p.124), so one iteration is enough for our purposes + */ + var tanBZero = (a*z) / (b * W); + var BZero = Math.atan((tanBZero)); + var tanPhi = (z + (ePrimeSquared * b * (Math.pow(Math.sin(BZero), 3))) ) /(W - (a * eSquared * (Math.pow(Math.cos(BZero), 3)))); + var phi = Math.atan(tanPhi); + answer[0] = phi; + /** + * Latitude done, now get the elevation. Note: The handbook states that near the poles, it is preferable to use + * h = (Z / sin phi ) - rSubN + (eSquared * rSubN). Our applications are never near the poles, so this formula + * was left unimplemented. + */ + rSubN = (a*a) / Math.sqrt(((a*a) * (Math.cos(phi)*Math.cos(phi)) + ((b*b) * (Math.sin(phi)*Math.sin(phi))))); + + answer[2] = (W / Math.cos(phi)) - rSubN; + + var ld = answer[0] * this.DEGREES_PER_RADIAN; + var lnd = answer[1] * this.DEGREES_PER_RADIAN; + var result = {latitude:ld, longitude:lnd, altitude:answer[2]}; + return result; + + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {x:y:z:} ecefPosition ecef position (in meters) + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFObjectToENU = function(ecefPosition) + { + return this.ECEFtoENU(ecefPosition.x, ecefPosition.y, ecefPosition.z); + }; + + /** + * Converts an ECEF position to the local ENU coordinate system. Units are meters, + * and the origin of the ENU coordinate system is set in the constructor. + * + * @param {float} X the X coordinate of the ECEF position + * @param {float} Y the Y coordinate + * @param {float} Z the Z coordinate + * @returns {x:y:z:} object with x, y, and z local coordinates, ENU + */ + dis.RangeCoordinates.prototype.ECEFtoENU = function(X, Y, Z) + { + // Origin of ENU tangent plane coordinate system in ECEF coordinate system + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var originLonRadians = this.ENUOrigin.longitude * this.RADIANS_PER_DEGREE; + var originLatRadians = this.ENUOrigin.latitude * this.RADIANS_PER_DEGREE; + + e = -(Math.sin(originLonRadians)) * (X-Xr) + Math.cos(originLonRadians) * (Y-Yr); + n = -(Math.sin(originLatRadians)) * Math.cos(originLonRadians) * (X-Xr) - Math.sin(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.cos(originLatRadians) * (Z-Zr); + u = Math.cos(originLatRadians) * Math.cos(originLonRadians) * (X-Xr) + Math.cos(originLatRadians) * Math.sin(originLonRadians) * (Y-Yr) + Math.sin(originLatRadians) * (Z-Zr); + + // Local coordinate system x, y, z + return {x:e, y:n, z:u}; + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane object to ECEF, aka DIS coordinates. + * + * @param enuPosition {x:y:z:} local coordinate object + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUObjectToECEF = function(enuPosition) + { + return this.ENUtoECEF(enuPosition.x, enuPosition.y, enuPosition.z); + }; + + /** + * Converts a local coordinate system / ENU/ Local Tangent Plane point to ECEF, aka DIS coordinates. + * + * @param localX {float} local coordinate system X + * @param localY {float} local coordinate system Y + * @param localZ {float} local coordinate system Z + * @returns {x:y:z:} point in ECEF / DIS coordinate system + */ + dis.RangeCoordinates.prototype.ENUtoECEF = function(localX, localY, localZ) + { + // ENU local coordinate system origin, in ECEF + var Xr = this.ENUOriginInECEF.x; + var Yr = this.ENUOriginInECEF.y; + var Zr = this.ENUOriginInECEF.z; + + var refLong = this.ENUOrigin.longitude; + var refLat = this.ENUOrigin.latitude; + + /** original code this was copied from + + function [X, Y, Z] = enu2xyz(refLat, refLong, refH, e, n, u) + % Convert east, north, up coordinates (labeled e, n, u) to ECEF + % coordinates. The reference point (phi, lambda, h) must be given. All distances are in metres + + [Xr,Yr,Zr] = llh2xyz(refLat,refLong, refH); % location of reference point + + X = -sin(refLong)*e - cos(refLong)*sin(refLat)*n + cos(refLong)*cos(refLat)*u + Xr; + Y = cos(refLong)*e - sin(refLong)*sin(refLat)*n + cos(refLat)*sin(refLong)*u + Yr; + Z = cos(refLat)*n + sin(refLat)*u + Zr; + */ + + X = -(Math.sin(refLong)) * localX - Math.cos(refLong) * Math.sin(refLat) * localY + Math.cos(refLong) * Math.cos(refLat) * localZ + Xr; + Y = Math.cos(refLong) * localX - Math.sin(refLong) * Math.sin(refLat) * localY + Math.cos(refLat) * Math.sin(refLong) * localZ + Yr; + Z = Math.cos(refLat) * localY + Math.sin(refLat) * localZ + Zr; + + return {x:X, y:Y, z:Z}; + }; + +exports.RangeCoordinates = dis.RangeCoordinates;if (typeof dis === "undefined") + dis = {}; + +// Support for node.js style modules; ignore if not using node.js require +if (typeof exports === "undefined") + exports = {}; + +/** + * Utility class that converts between strings and the DIS ESPDU marking + * field. The marking field is 12 bytes long, with the first byte being + * the character set used, and the remaining 11 bytes character codes in + * that character set. This is often used for debugging or "billboard" + * displays in 3D; it's intended for humans. The string character values + * are clamped (or filled) to exactly 11 bytes, so "This is a long string" + * will be clamped to "This is a l" (in charachter codes) and "foo" will + * be filled to "foo\0\0\0\0\0\0\0\0".<p> + * + * It is recommended that only ASCII character set (character set = 1) + * be used. + * + * @returns {undefined} + */ +dis.StringConversion = function() +{ +}; + +/** + * Given a string, returns a DIS marking field. The character set is set to + * 1, for ascii. The length is clamped to 11, and zero-filled if the string + * is shorter than 11. + * + * @returns {array} disMarking field, 12 bytes long, character set = 1 (ascii) in 0, zero-filled to 11 character codes + */ +dis.StringConversion.prototype.StringToDisMarking = function(markingString) +{ + var byteMarking = []; + + // character set 1 = ascii + byteMarking.push(1); + + var markingLength = markingString.length; + + // Clamp it to 11 bytes of character data + if(markingLength > 11) + markingLength = 11; + + // If the string is shorter than 11 bytes, we zero-fill the array + var diff = 11 - markingLength; + + for(var idx = 0; idx < markingLength; idx++) + { + byteMarking.push(markingString.charCodeAt(idx)); + } + + for(var idx = markingLength; idx < 11; idx++) + { + byteMarking.push(0); + } + + return byteMarking; +}; + +/** + * Given a DIS marking field, returns a string. Assumes always ascii. + * + * @param {array} disMarking dis marking field, [0] = character set, the rest character codes + * @returns {string} string equivalent of the marking field + */ +dis.StringConversion.prototype.DisMarkingToString = function(disMarking) +{ + var marking = ""; + + for(var idx = 1; idx < disMarking.length; idx++) + { + marking = marking + String.fromCharCode(disMarking[idx]); + } + + return marking; +}; + +// This is a temporary placeholder until full require.js code +// support is present. +if (typeof exports === "undefined") + exports = {}; + +exports.RangeCoordinates = dis.RangeCoordinates; +exports.InputStream = dis.InputStream; +exports.OutputStream = dis.OutputStream; + +/** + * Section 5.3.6.5. Acknowledge the receiptof a start/resume, stop/freeze, or RemoveEntityPDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 15; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** type of message being acknowledged */ + this.acknowledgeFlag = 0; + + /** Whether or not the receiving entity was able to comply with the request */ + this.responseFlag = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.AcknowledgePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgePdu = dis.AcknowledgePdu; + +// End of AcknowledgePdu class + +/** + * Section 5.3.12.5: Ack receipt of a start-resume, stop-freeze, create-entity or remove enitty (reliable) pdus. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcknowledgeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 55; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** ack flags */ + this.acknowledgeFlag = 0; + + /** response flags */ + this.responseFlag = 0; + + /** Request ID */ + this.requestID = 0; + + dis.AcknowledgeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.acknowledgeFlag = inputStream.readUShort(); + this.responseFlag = inputStream.readUShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.AcknowledgeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.acknowledgeFlag); + outputStream.writeUShort(this.responseFlag); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.AcknowledgeReliablePdu = dis.AcknowledgeReliablePdu; + +// End of AcknowledgeReliablePdu class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamData = function() +{ + /** beam data length */ + this.beamDataLength = 0; + + /** beamIDNumber */ + this.beamIDNumber = 0; + + /** padding */ + this.pad2 = 0; + + /** fundamental data parameters */ + this.fundamentalDataParameters = new dis.AcousticBeamFundamentalParameter(); + + dis.AcousticBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUShort(); + this.beamIDNumber = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.fundamentalDataParameters.initFromBinary(inputStream); + }; + + dis.AcousticBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.pad2); + this.fundamentalDataParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamData = dis.AcousticBeamData; + +// End of AcousticBeamData class + +/** + * Used in UaPdu + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticBeamFundamentalParameter = function() +{ + /** parameter index */ + this.activeEmissionParameterIndex = 0; + + /** scan pattern */ + this.scanPattern = 0; + + /** beam center azimuth */ + this.beamCenterAzimuth = 0; + + /** azimuthal beamwidth */ + this.azimuthalBeamwidth = 0; + + /** beam center */ + this.beamCenterDE = 0; + + /** DE beamwidth (vertical beamwidth) */ + this.deBeamwidth = 0; + + dis.AcousticBeamFundamentalParameter.prototype.initFromBinary = function(inputStream) + { + this.activeEmissionParameterIndex = inputStream.readUShort(); + this.scanPattern = inputStream.readUShort(); + this.beamCenterAzimuth = inputStream.readFloat32(); + this.azimuthalBeamwidth = inputStream.readFloat32(); + this.beamCenterDE = inputStream.readFloat32(); + this.deBeamwidth = inputStream.readFloat32(); + }; + + dis.AcousticBeamFundamentalParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.activeEmissionParameterIndex); + outputStream.writeUShort(this.scanPattern); + outputStream.writeFloat32(this.beamCenterAzimuth); + outputStream.writeFloat32(this.azimuthalBeamwidth); + outputStream.writeFloat32(this.beamCenterDE); + outputStream.writeFloat32(this.deBeamwidth); + }; +}; // end of class + + // node.js module support +exports.AcousticBeamFundamentalParameter = dis.AcousticBeamFundamentalParameter; + +// End of AcousticBeamFundamentalParameter class + +/** + * Section 5.2.35. information about a specific UA emmtter + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitter = function() +{ + /** the system for a particular UA emitter, and an enumeration */ + this.acousticName = 0; + + /** The function of the acoustic system */ + this.function = 0; + + /** The UA emitter identification number relative to a specific system */ + this.acousticIdNumber = 0; + + dis.AcousticEmitter.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.acousticIdNumber = inputStream.readUByte(); + }; + + dis.AcousticEmitter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.acousticIdNumber); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitter = dis.AcousticEmitter; + +// End of AcousticEmitter class + +/** + * 5.3.35: Information about a particular UA emitter shall be represented using an Acoustic Emitter System record. This record shall consist of three fields: Acoustic Name, Function, and Acoustic ID Number + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystem = function() +{ + /** This field shall specify the system for a particular UA emitter. */ + this.acousticName = 0; + + /** This field shall describe the function of the acoustic system. */ + this.acousticFunction = 0; + + /** This field shall specify the UA emitter identification number relative to a specific system. This field shall be represented by an 8-bit unsigned integer. This field allows the differentiation of multiple systems on an entity, even if in some instances two or more of the systems may be identical UA emitter types. Numbering of systems shall begin with the value 1. */ + this.acousticID = 0; + + dis.AcousticEmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.acousticName = inputStream.readUShort(); + this.acousticFunction = inputStream.readUByte(); + this.acousticID = inputStream.readUByte(); + }; + + dis.AcousticEmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.acousticName); + outputStream.writeUByte(this.acousticFunction); + outputStream.writeUByte(this.acousticID); + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystem = dis.AcousticEmitterSystem; + +// End of AcousticEmitterSystem class + +/** + * Used in the UA pdu; ties together an emmitter and a location. This requires manual cleanup; the beam data should not be attached to each emitter system. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AcousticEmitterSystemData = function() +{ + /** Length of emitter system data */ + this.emitterSystemDataLength = 0; + + /** Number of beams */ + this.numberOfBeams = 0; + + /** padding */ + this.pad2 = 0; + + /** This field shall specify the system for a particular UA emitter. */ + this.acousticEmitterSystem = new dis.AcousticEmitterSystem(); + + /** Represents the location wrt the entity */ + this.emitterLocation = new dis.Vector3Float(); + + /** For each beam in numberOfBeams, an emitter system. This is not right--the beam records need to be at the end of the PDU, rather than attached to each system. */ + this.beamRecords = new Array(); + + dis.AcousticEmitterSystemData.prototype.initFromBinary = function(inputStream) + { + this.emitterSystemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.acousticEmitterSystem.initFromBinary(inputStream); + this.emitterLocation.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.AcousticBeamData(); + anX.initFromBinary(inputStream); + this.beamRecords.push(anX); + } + + }; + + dis.AcousticEmitterSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.emitterSystemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.pad2); + this.acousticEmitterSystem.encodeToBinary(outputStream); + this.emitterLocation.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamRecords.length; idx++) + { + beamRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AcousticEmitterSystemData = dis.AcousticEmitterSystemData; + +// End of AcousticEmitterSystemData class + +/** + * Section 5.3.6.6. Request from simulation manager to an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 16; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** identifies the action being requested */ + this.actionID = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestPdu = dis.ActionRequestPdu; + +// End of ActionRequestPdu class + +/** + * Section 5.3.12.6: request from a simulation manager to a managed entity to perform a specified action. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionRequestReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 56; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** request ID */ + this.actionID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionRequestReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.actionID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionRequestReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.actionID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionRequestReliablePdu = dis.ActionRequestReliablePdu; + +// End of ActionRequestReliablePdu class + +/** + * Section 5.3.6.7. response to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 17; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID that is unique */ + this.requestID = 0; + + /** Status of response */ + this.requestStatus = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.ActionResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requestStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.ActionResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.requestStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponsePdu = dis.ActionResponsePdu; + +// End of ActionResponsePdu class + +/** + * Section 5.3.12.7: Response from an entity to an action request PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ActionResponseReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 57; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** status of response */ + this.responseStatus = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.ActionResponseReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.responseStatus = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.ActionResponseReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.responseStatus); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ActionResponseReliablePdu = dis.ActionResponseReliablePdu; + +// End of ActionResponseReliablePdu class + +/** + * Section 5.2.36. Each agregate in a given simulation app is given an aggregate identifier number unique for all other aggregates in that app and in that exercise. The id is valid for the duration of the the exercise. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the aggregate ID */ + this.aggregateID = 0; + + dis.AggregateID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.aggregateID = inputStream.readUShort(); + }; + + dis.AggregateID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.aggregateID); + }; +}; // end of class + + // node.js module support +exports.AggregateID = dis.AggregateID; + +// End of AggregateID class + +/** + * Section 5.2.37. Specifies the character set used inthe first byte, followed by up to 31 characters of text data. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateMarking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.AggregateMarking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 31; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.AggregateMarking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 31; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.AggregateMarking = dis.AggregateMarking; + +// End of AggregateMarking class + +/** + * Section 5.3.9.1 informationa bout aggregating entities anc communicating information about the aggregated entities. requires manual intervention to fix the padding between entityID lists and silent aggregate sysem lists--this padding is dependent on how many entityIDs there are, and needs to be on a 32 bit word boundary. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 33; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.aggregateID = new dis.EntityID(); + + /** force ID */ + this.forceID = 0; + + /** state of aggregate */ + this.aggregateState = 0; + + /** entity type of the aggregated entities */ + this.aggregateType = new dis.EntityType(); + + /** formation of aggregated entities */ + this.formation = 0; + + /** marking for aggregate; first char is charset type, rest is char data */ + this.aggregateMarking = new dis.AggregateMarking(); + + /** dimensions of bounding box for the aggregated entities, origin at the center of mass */ + this.dimensions = new dis.Vector3Float(); + + /** orientation of the bounding box */ + this.orientation = new dis.Orientation(); + + /** center of mass of the aggregation */ + this.centerOfMass = new dis.Vector3Double(); + + /** velocity of aggregation */ + this.velocity = new dis.Vector3Float(); + + /** number of aggregates */ + this.numberOfDisAggregates = 0; + + /** number of entities */ + this.numberOfDisEntities = 0; + + /** number of silent aggregate types */ + this.numberOfSilentAggregateTypes = 0; + + /** number of silent entity types */ + this.numberOfSilentEntityTypes = 0; + + /** aggregates list */ + this.aggregateIDList = new Array(); + + /** entity ID list */ + this.entityIDList = new Array(); + + /** ^^^padding to put the start of the next list on a 32 bit boundary. This needs to be fixed */ + this.pad2 = 0; + + /** silent entity types */ + this.silentAggregateSystemList = new Array(); + + /** silent entity types */ + this.silentEntitySystemList = new Array(); + + /** number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variableDatums */ + this.variableDatumList = new Array(); + + dis.AggregateStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.aggregateID.initFromBinary(inputStream); + this.forceID = inputStream.readUByte(); + this.aggregateState = inputStream.readUByte(); + this.aggregateType.initFromBinary(inputStream); + this.formation = inputStream.readUInt(); + this.aggregateMarking.initFromBinary(inputStream); + this.dimensions.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.centerOfMass.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.numberOfDisAggregates = inputStream.readUShort(); + this.numberOfDisEntities = inputStream.readUShort(); + this.numberOfSilentAggregateTypes = inputStream.readUShort(); + this.numberOfSilentEntityTypes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfDisAggregates; idx++) + { + var anX = new dis.AggregateID(); + anX.initFromBinary(inputStream); + this.aggregateIDList.push(anX); + } + + for(var idx = 0; idx < this.numberOfDisEntities; idx++) + { + var anX = new dis.EntityID(); + anX.initFromBinary(inputStream); + this.entityIDList.push(anX); + } + + this.pad2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfSilentAggregateTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentAggregateSystemList.push(anX); + } + + for(var idx = 0; idx < this.numberOfSilentEntityTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.silentEntitySystemList.push(anX); + } + + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumList.push(anX); + } + + }; + + dis.AggregateStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.aggregateID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.aggregateState); + this.aggregateType.encodeToBinary(outputStream); + outputStream.writeUInt(this.formation); + this.aggregateMarking.encodeToBinary(outputStream); + this.dimensions.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + this.centerOfMass.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfDisAggregates); + outputStream.writeUShort(this.numberOfDisEntities); + outputStream.writeUShort(this.numberOfSilentAggregateTypes); + outputStream.writeUShort(this.numberOfSilentEntityTypes); + for(var idx = 0; idx < this.aggregateIDList.length; idx++) + { + aggregateIDList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.entityIDList.length; idx++) + { + entityIDList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad2); + for(var idx = 0; idx < this.silentAggregateSystemList.length; idx++) + { + silentAggregateSystemList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.silentEntitySystemList.length; idx++) + { + silentEntitySystemList[idx].encodeToBinary(outputStream); + } + + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.variableDatumList.length; idx++) + { + variableDatumList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.AggregateStatePdu = dis.AggregateStatePdu; + +// End of AggregateStatePdu class + +/** + * Section 5.2.38. Identifies the type of aggregate including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AggregateType = function() +{ + /** Kind of entity */ + this.aggregateKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field, sql has a reserved word for specific */ + this.specificInfo = 0; + + this.extra = 0; + + dis.AggregateType.prototype.initFromBinary = function(inputStream) + { + this.aggregateKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specificInfo = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.AggregateType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.aggregateKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specificInfo); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.AggregateType = dis.AggregateType; + +// End of AggregateType class + +/** + * 5.2.2: angular velocity measured in radians per second out each of the entity's own coordinate axes. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AngularVelocityVector = function() +{ + /** velocity about the x axis */ + this.x = 0; + + /** velocity about the y axis */ + this.y = 0; + + /** velocity about the zaxis */ + this.z = 0; + + dis.AngularVelocityVector.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.AngularVelocityVector.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.AngularVelocityVector = dis.AngularVelocityVector; + +// End of AngularVelocityVector class + +/** + * 5.2.3: location of the radiating portion of the antenna, specified in world coordinates and entity coordinates. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.AntennaLocation = function() +{ + /** Location of the radiating portion of the antenna in world coordinates */ + this.antennaLocation = new dis.Vector3Double(); + + /** Location of the radiating portion of the antenna in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + dis.AntennaLocation.prototype.initFromBinary = function(inputStream) + { + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + }; + + dis.AntennaLocation.prototype.encodeToBinary = function(outputStream) + { + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.AntennaLocation = dis.AntennaLocation; + +// End of AntennaLocation class + +/** + * Used in UA PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ApaData = function() +{ + /** Index of APA parameter */ + this.parameterIndex = 0; + + /** Index of APA parameter */ + this.parameterValue = 0; + + dis.ApaData.prototype.initFromBinary = function(inputStream) + { + this.parameterIndex = inputStream.readUShort(); + this.parameterValue = inputStream.readShort(); + }; + + dis.ApaData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.parameterIndex); + outputStream.writeShort(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ApaData = dis.ApaData; + +// End of ApaData class + +/** + * Section 5.3.11.5: Information about the addition/modification of an oobject that is geometrically achored to the terrain with a set of three or more points that come to a closure. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArealObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 45; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications enumeration */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.EntityType(); + + /** Object appearance */ + this.objectAppearance = new dis.SixByteChunk(); + + /** Number of points */ + this.numberOfPoints = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** location of object */ + this.objectLocation = new Array(); + + dis.ArealObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectAppearance.initFromBinary(inputStream); + this.numberOfPoints = inputStream.readUShort(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPoints; idx++) + { + var anX = new dis.Vector3Double(); + anX.initFromBinary(inputStream); + this.objectLocation.push(anX); + } + + }; + + dis.ArealObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectAppearance.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfPoints); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + for(var idx = 0; idx < this.objectLocation.length; idx++) + { + objectLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ArealObjectStatePdu = dis.ArealObjectStatePdu; + +// End of ArealObjectStatePdu class + +/** + * Section 5.2.5. Articulation parameters for movable parts and attached parts of an entity. Specifes wether or not a change has occured, the part identifcation of the articulated part to which it is attached, and the type and value of each parameter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ArticulationParameter = function() +{ + this.parameterTypeDesignator = 0; + + this.changeIndicator = 0; + + this.partAttachedTo = 0; + + this.parameterType = 0; + + this.parameterValue = 0; + + dis.ArticulationParameter.prototype.initFromBinary = function(inputStream) + { + this.parameterTypeDesignator = inputStream.readUByte(); + this.changeIndicator = inputStream.readUByte(); + this.partAttachedTo = inputStream.readUShort(); + this.parameterType = inputStream.readInt(); + this.parameterValue = inputStream.readFloat64(); + }; + + dis.ArticulationParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.parameterTypeDesignator); + outputStream.writeUByte(this.changeIndicator); + outputStream.writeUShort(this.partAttachedTo); + outputStream.writeInt(this.parameterType); + outputStream.writeFloat64(this.parameterValue); + }; +}; // end of class + + // node.js module support +exports.ArticulationParameter = dis.ArticulationParameter; + +// End of ArticulationParameter class + +/** + * Section 5.2.4.2. Used when the antenna pattern type field has a value of 1. Specifies the direction, patter, and polarization of radiation from an antenna. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamAntennaPattern = function() +{ + /** The rotation that transformst he reference coordinate sytem into the beam coordinate system. Either world coordinates or entity coordinates may be used as the reference coordinate system, as specified by teh reference system field of the antenna pattern record. */ + this.beamDirection = new dis.Orientation(); + + this.azimuthBeamwidth = 0; + + this.elevationBeamwidth = 0; + + this.referenceSystem = 0; + + this.padding1 = 0; + + this.padding2 = 0; + + /** Magnigute of the z-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ez = 0; + + /** Magnigute of the x-component in beam coordinates at some arbitrary single point in the mainbeam and in the far field of the antenna. */ + this.ex = 0; + + /** THe phase angle between Ez and Ex in radians. */ + this.phase = 0; + + dis.BeamAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.beamDirection.initFromBinary(inputStream); + this.azimuthBeamwidth = inputStream.readFloat32(); + this.elevationBeamwidth = inputStream.readFloat32(); + this.referenceSystem = inputStream.readFloat32(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + this.ez = inputStream.readFloat32(); + this.ex = inputStream.readFloat32(); + this.phase = inputStream.readFloat32(); + }; + + dis.BeamAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + this.beamDirection.encodeToBinary(outputStream); + outputStream.writeFloat32(this.azimuthBeamwidth); + outputStream.writeFloat32(this.elevationBeamwidth); + outputStream.writeFloat32(this.referenceSystem); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + outputStream.writeFloat32(this.ez); + outputStream.writeFloat32(this.ex); + outputStream.writeFloat32(this.phase); + }; +}; // end of class + + // node.js module support +exports.BeamAntennaPattern = dis.BeamAntennaPattern; + +// End of BeamAntennaPattern class + +/** + * Section 5.2.39. Specification of the data necessary to describe the scan volume of an emitter. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BeamData = function() +{ + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.BeamData.prototype.initFromBinary = function(inputStream) + { + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.BeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.BeamData = dis.BeamData; + +// End of BeamData class + +/** + * Section 5.2.7. Specifies the type of muntion fired, the type of warhead, the type of fuse, the number of rounds fired, and the rate at which the roudns are fired in rounds per minute. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.BurstDescriptor = function() +{ + /** What munition was used in the burst */ + this.munition = new dis.EntityType(); + + /** type of warhead */ + this.warhead = 0; + + /** type of fuse used */ + this.fuse = 0; + + /** how many of the munition were fired */ + this.quantity = 0; + + /** rate at which the munition was fired */ + this.rate = 0; + + dis.BurstDescriptor.prototype.initFromBinary = function(inputStream) + { + this.munition.initFromBinary(inputStream); + this.warhead = inputStream.readUShort(); + this.fuse = inputStream.readUShort(); + this.quantity = inputStream.readUShort(); + this.rate = inputStream.readUShort(); + }; + + dis.BurstDescriptor.prototype.encodeToBinary = function(outputStream) + { + this.munition.encodeToBinary(outputStream); + outputStream.writeUShort(this.warhead); + outputStream.writeUShort(this.fuse); + outputStream.writeUShort(this.quantity); + outputStream.writeUShort(this.rate); + }; +}; // end of class + + // node.js module support +exports.BurstDescriptor = dis.BurstDescriptor; + +// End of BurstDescriptor class + +/** + * Section 5.2.8. Time measurements that exceed one hour. Hours is the number of hours since January 1, 1970, UTC + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ClockTime = function() +{ + /** Hours in UTC */ + this.hour = 0; + + /** Time past the hour */ + this.timePastHour = 0; + + dis.ClockTime.prototype.initFromBinary = function(inputStream) + { + this.hour = inputStream.readInt(); + this.timePastHour = inputStream.readUInt(); + }; + + dis.ClockTime.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.hour); + outputStream.writeUInt(this.timePastHour); + }; +}; // end of class + + // node.js module support +exports.ClockTime = dis.ClockTime; + +// End of ClockTime class + +/** + * 5.3.3.3. Information about elastic collisions in a DIS exercise shall be communicated using a Collision-Elastic PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionElasticPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 66; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.collisionEventID = new dis.EventID(); + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.contactVelocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + /** tensor values */ + this.collisionResultXX = 0; + + /** tensor values */ + this.collisionResultXY = 0; + + /** tensor values */ + this.collisionResultXZ = 0; + + /** tensor values */ + this.collisionResultYY = 0; + + /** tensor values */ + this.collisionResultYZ = 0; + + /** tensor values */ + this.collisionResultZZ = 0; + + /** This record shall represent the normal vector to the surface at the point of collision detection. The surface normal shall be represented in world coordinates. */ + this.unitSurfaceNormal = new dis.Vector3Float(); + + /** This field shall represent the degree to which energy is conserved in a collision */ + this.coefficientOfRestitution = 0; + + dis.CollisionElasticPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.collisionEventID.initFromBinary(inputStream); + this.pad = inputStream.readShort(); + this.contactVelocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + this.collisionResultXX = inputStream.readFloat32(); + this.collisionResultXY = inputStream.readFloat32(); + this.collisionResultXZ = inputStream.readFloat32(); + this.collisionResultYY = inputStream.readFloat32(); + this.collisionResultYZ = inputStream.readFloat32(); + this.collisionResultZZ = inputStream.readFloat32(); + this.unitSurfaceNormal.initFromBinary(inputStream); + this.coefficientOfRestitution = inputStream.readFloat32(); + }; + + dis.CollisionElasticPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.collisionEventID.encodeToBinary(outputStream); + outputStream.writeShort(this.pad); + this.contactVelocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + outputStream.writeFloat32(this.collisionResultXX); + outputStream.writeFloat32(this.collisionResultXY); + outputStream.writeFloat32(this.collisionResultXZ); + outputStream.writeFloat32(this.collisionResultYY); + outputStream.writeFloat32(this.collisionResultYZ); + outputStream.writeFloat32(this.collisionResultZZ); + this.unitSurfaceNormal.encodeToBinary(outputStream); + outputStream.writeFloat32(this.coefficientOfRestitution); + }; +}; // end of class + + // node.js module support +exports.CollisionElasticPdu = dis.CollisionElasticPdu; + +// End of CollisionElasticPdu class + +/** + * Section 5.3.3.2. Information about a collision. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CollisionPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 4; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that issued the collision PDU */ + this.issuingEntityID = new dis.EntityID(); + + /** ID of entity that has collided with the issuing entity ID */ + this.collidingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** ID of event */ + this.collisionType = 0; + + /** some padding */ + this.pad = 0; + + /** velocity at collision */ + this.velocity = new dis.Vector3Float(); + + /** mass of issuing entity */ + this.mass = 0; + + /** Location with respect to entity the issuing entity collided with */ + this.location = new dis.Vector3Float(); + + dis.CollisionPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.issuingEntityID.initFromBinary(inputStream); + this.collidingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.collisionType = inputStream.readUByte(); + this.pad = inputStream.readByte(); + this.velocity.initFromBinary(inputStream); + this.mass = inputStream.readFloat32(); + this.location.initFromBinary(inputStream); + }; + + dis.CollisionPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.issuingEntityID.encodeToBinary(outputStream); + this.collidingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.collisionType); + outputStream.writeByte(this.pad); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.mass); + this.location.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.CollisionPdu = dis.CollisionPdu; + +// End of CollisionPdu class + +/** + * Section 5.3.6.12. Arbitrary messages can be entered into the data stream via use of this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 22; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.CommentPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.CommentPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentPdu = dis.CommentPdu; + +// End of CommentPdu class + +/** + * Section 5.3.12.12: Arbitrary messages. Only reliable this time. Neds manual intervention to fix padding in variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CommentReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 62; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.CommentReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.CommentReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.CommentReliablePdu = dis.CommentReliablePdu; + +// End of CommentReliablePdu class + +/** + * Section 5.3.6.1. Create a new entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 11; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.CreateEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityPdu = dis.CreateEntityPdu; + +// End of CreateEntityPdu class + +/** + * Section 5.3.12.1: creation of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.CreateEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 51; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.CreateEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.CreateEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.CreateEntityReliablePdu = dis.CreateEntityReliablePdu; + +// End of CreateEntityReliablePdu class + +/** + * Section 5.3.6.10. Information issued in response to a data query pdu or a set data pdu is communicated using a data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 20; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataPdu = dis.DataPdu; + +// End of DataPdu class + +/** + * Section 5.3.6.8. Request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 18; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** time issues between issues of Data PDUs. Zero means send once only. */ + this.timeInterval = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.DataQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.UnsignedIntegerWrapper(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.DataQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryPdu = dis.DataQueryPdu; + +// End of DataQueryPdu class + +/** + * Section 5.3.12.8: request for data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 58; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** request ID */ + this.requestID = 0; + + /** time interval between issuing data query PDUs */ + this.timeInterval = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.timeInterval = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.timeInterval); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataQueryReliablePdu = dis.DataQueryReliablePdu; + +// End of DataQueryReliablePdu class + +/** + * Section 5.3.12.10: issued in response to a data query R or set dataR pdu. Needs manual intervention to fix padding on variable datums. UNFINSIHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 60; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.DataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.DataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DataReliablePdu = dis.DataReliablePdu; + +// End of DataReliablePdu class + +/** + * represents values used in dead reckoning algorithms + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DeadReckoningParameter = function() +{ + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Linear acceleration of the entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + /** angular velocity of the entity */ + this.entityAngularVelocity = new dis.Vector3Float(); + + dis.DeadReckoningParameter.prototype.initFromBinary = function(inputStream) + { + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.entityLinearAcceleration.initFromBinary(inputStream); + this.entityAngularVelocity.initFromBinary(inputStream); + }; + + dis.DeadReckoningParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + this.entityLinearAcceleration.encodeToBinary(outputStream); + this.entityAngularVelocity.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DeadReckoningParameter = dis.DeadReckoningParameter; + +// End of DeadReckoningParameter class + +/** + * Section 5.3.7.2. Handles designating operations. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DesignatorPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 24; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity designating */ + this.designatingEntityID = new dis.EntityID(); + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.codeName = 0; + + /** ID of the entity being designated */ + this.designatedEntityID = new dis.EntityID(); + + /** This field shall identify the designator code being used by the designating entity */ + this.designatorCode = 0; + + /** This field shall identify the designator output power in watts */ + this.designatorPower = 0; + + /** This field shall identify the designator wavelength in units of microns */ + this.designatorWavelength = 0; + + /** designtor spot wrt the designated entity */ + this.designatorSpotWrtDesignated = new dis.Vector3Float(); + + /** designtor spot wrt the designated entity */ + this.designatorSpotLocation = new dis.Vector3Double(); + + /** Dead reckoning algorithm */ + this.deadReckoningAlgorithm = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** linear accelleration of entity */ + this.entityLinearAcceleration = new dis.Vector3Float(); + + dis.DesignatorPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.designatingEntityID.initFromBinary(inputStream); + this.codeName = inputStream.readUShort(); + this.designatedEntityID.initFromBinary(inputStream); + this.designatorCode = inputStream.readUShort(); + this.designatorPower = inputStream.readFloat32(); + this.designatorWavelength = inputStream.readFloat32(); + this.designatorSpotWrtDesignated.initFromBinary(inputStream); + this.designatorSpotLocation.initFromBinary(inputStream); + this.deadReckoningAlgorithm = inputStream.readByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readByte(); + this.entityLinearAcceleration.initFromBinary(inputStream); + }; + + dis.DesignatorPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.designatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.codeName); + this.designatedEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.designatorCode); + outputStream.writeFloat32(this.designatorPower); + outputStream.writeFloat32(this.designatorWavelength); + this.designatorSpotWrtDesignated.encodeToBinary(outputStream); + this.designatorSpotLocation.encodeToBinary(outputStream); + outputStream.writeByte(this.deadReckoningAlgorithm); + outputStream.writeUShort(this.padding1); + outputStream.writeByte(this.padding2); + this.entityLinearAcceleration.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.DesignatorPdu = dis.DesignatorPdu; + +// End of DesignatorPdu class + +/** + * Section 5.3.4.2. Information about stuff exploding. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DetonationPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 3; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of muntion that was fired */ + this.munitionID = new dis.EntityID(); + + /** ID firing event */ + this.eventID = new dis.EventID(); + + /** ID firing event */ + this.velocity = new dis.Vector3Float(); + + /** where the detonation is, in world coordinates */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munition used */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** location of the detonation or impact in the target entity's coordinate system. This information should be used for damage assessment. */ + this.locationInEntityCoordinates = new dis.Vector3Float(); + + /** result of the explosion */ + this.detonationResult = 0; + + /** How many articulation parameters we have */ + this.numberOfArticulationParameters = 0; + + /** padding */ + this.pad = 0; + + this.articulationParameters = new Array(); + + dis.DetonationPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.locationInEntityCoordinates.initFromBinary(inputStream); + this.detonationResult = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.pad = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.DetonationPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.locationInEntityCoordinates.encodeToBinary(outputStream); + outputStream.writeUByte(this.detonationResult); + outputStream.writeUByte(this.numberOfArticulationParameters); + outputStream.writeShort(this.pad); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.DetonationPdu = dis.DetonationPdu; + +// End of DetonationPdu class + +/** + * Section 5.3.7. Electronic Emissions. Abstract superclass for distirubted emissions PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.DistributedEmissionsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.DistributedEmissionsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.DistributedEmissionsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.DistributedEmissionsFamilyPdu = dis.DistributedEmissionsFamilyPdu; + +// End of DistributedEmissionsFamilyPdu class + +/** + * 64 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EightByteChunk = function() +{ + /** Eight bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0); + + dis.EightByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 8; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.EightByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 8; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.EightByteChunk = dis.EightByteChunk; + +// End of EightByteChunk class + +/** + * Description of one electronic emission beam + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionBeamData = function() +{ + /** This field shall specify the length of this beams data in 32 bit words */ + this.beamDataLength = 0; + + /** This field shall specify a unique emitter database number assigned to differentiate between otherwise similar or identical emitter beams within an emitter system. */ + this.beamIDNumber = 0; + + /** This field shall specify a Beam Parameter Index number that shall be used by receiving entities in conjunction with the Emitter Name field to provide a pointer to the stored database parameters required to regenerate the beam. */ + this.beamParameterIndex = 0; + + /** Fundamental parameter data such as frequency range, beam sweep, etc. */ + this.fundamentalParameterData = new dis.FundamentalParameterData(); + + /** beam function of a particular beam */ + this.beamFunction = 0; + + /** Number of track/jam targets */ + this.numberOfTrackJamTargets = 0; + + /** wheher or not the receiving simulation apps can assume all the targets in the scan pattern are being tracked/jammed */ + this.highDensityTrackJam = 0; + + /** padding */ + this.pad4 = 0; + + /** identify jamming techniques used */ + this.jammingModeSequence = 0; + + /** variable length variablelist of track/jam targets */ + this.trackJamTargets = new Array(); + + dis.ElectronicEmissionBeamData.prototype.initFromBinary = function(inputStream) + { + this.beamDataLength = inputStream.readUByte(); + this.beamIDNumber = inputStream.readUByte(); + this.beamParameterIndex = inputStream.readUShort(); + this.fundamentalParameterData.initFromBinary(inputStream); + this.beamFunction = inputStream.readUByte(); + this.numberOfTrackJamTargets = inputStream.readUByte(); + this.highDensityTrackJam = inputStream.readUByte(); + this.pad4 = inputStream.readUByte(); + this.jammingModeSequence = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfTrackJamTargets; idx++) + { + var anX = new dis.TrackJamTarget(); + anX.initFromBinary(inputStream); + this.trackJamTargets.push(anX); + } + + }; + + dis.ElectronicEmissionBeamData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.beamDataLength); + outputStream.writeUByte(this.beamIDNumber); + outputStream.writeUShort(this.beamParameterIndex); + this.fundamentalParameterData.encodeToBinary(outputStream); + outputStream.writeUByte(this.beamFunction); + outputStream.writeUByte(this.numberOfTrackJamTargets); + outputStream.writeUByte(this.highDensityTrackJam); + outputStream.writeUByte(this.pad4); + outputStream.writeUInt(this.jammingModeSequence); + for(var idx = 0; idx < this.trackJamTargets.length; idx++) + { + trackJamTargets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionBeamData = dis.ElectronicEmissionBeamData; + +// End of ElectronicEmissionBeamData class + +/** + * Data about one electronic system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionSystemData = function() +{ + /** This field shall specify the length of this emitter system�s data (including beam data and its track/jam information) in 32-bit words. The length shall include the System Data Length field. */ + this.systemDataLength = 0; + + /** This field shall specify the number of beams being described in the current PDU for the system being described. */ + this.numberOfBeams = 0; + + /** padding. */ + this.emissionsPadding2 = 0; + + /** This field shall specify information about a particular emitter system */ + this.emitterSystem = new dis.EmitterSystem(); + + /** Location with respect to the entity */ + this.location = new dis.Vector3Float(); + + /** variable length variablelist of beam data records */ + this.beamDataRecords = new Array(); + + dis.ElectronicEmissionSystemData.prototype.initFromBinary = function(inputStream) + { + this.systemDataLength = inputStream.readUByte(); + this.numberOfBeams = inputStream.readUByte(); + this.emissionsPadding2 = inputStream.readUShort(); + this.emitterSystem.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfBeams; idx++) + { + var anX = new dis.ElectronicEmissionBeamData(); + anX.initFromBinary(inputStream); + this.beamDataRecords.push(anX); + } + + }; + + dis.ElectronicEmissionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemDataLength); + outputStream.writeUByte(this.numberOfBeams); + outputStream.writeUShort(this.emissionsPadding2); + this.emitterSystem.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + for(var idx = 0; idx < this.beamDataRecords.length; idx++) + { + beamDataRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionSystemData = dis.ElectronicEmissionSystemData; + +// End of ElectronicEmissionSystemData class + +/** + * Section 5.3.7.1. Information about active electronic warfare (EW) emissions and active EW countermeasures shall be communicated using an Electromagnetic Emission PDU. COMPLETE (I think) + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ElectronicEmissionsPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 23; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity emitting */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate if the data in the PDU represents a state update or just data that has changed since issuance of the last Electromagnetic Emission PDU [relative to the identified entity and emission system(s)]. */ + this.stateUpdateIndicator = 0; + + /** This field shall specify the number of emission systems being described in the current PDU. */ + this.numberOfSystems = 0; + + /** padding */ + this.paddingForEmissionsPdu = 0; + + /** Electronic emmissions systems */ + this.systems = new Array(); + + dis.ElectronicEmissionsPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateUpdateIndicator = inputStream.readUByte(); + this.numberOfSystems = inputStream.readUByte(); + this.paddingForEmissionsPdu = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfSystems; idx++) + { + var anX = new dis.ElectronicEmissionSystemData(); + anX.initFromBinary(inputStream); + this.systems.push(anX); + } + + }; + + dis.ElectronicEmissionsPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeUByte(this.stateUpdateIndicator); + outputStream.writeUByte(this.numberOfSystems); + outputStream.writeUShort(this.paddingForEmissionsPdu); + for(var idx = 0; idx < this.systems.length; idx++) + { + systems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ElectronicEmissionsPdu = dis.ElectronicEmissionsPdu; + +// End of ElectronicEmissionsPdu class + +/** + * Section 5.2.11. This field shall specify information about a particular emitter system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EmitterSystem = function() +{ + /** Name of the emitter, 16 bit enumeration */ + this.emitterName = 0; + + /** function of the emitter, 8 bit enumeration */ + this.function = 0; + + /** emitter ID, 8 bit enumeration */ + this.emitterIdNumber = 0; + + dis.EmitterSystem.prototype.initFromBinary = function(inputStream) + { + this.emitterName = inputStream.readUShort(); + this.function = inputStream.readUByte(); + this.emitterIdNumber = inputStream.readUByte(); + }; + + dis.EmitterSystem.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.emitterName); + outputStream.writeUByte(this.function); + outputStream.writeUByte(this.emitterIdNumber); + }; +}; // end of class + + // node.js module support +exports.EmitterSystem = dis.EmitterSystem; + +// End of EmitterSystem class + +/** + * Each entity in a given DIS simulation application shall be given an entity identifier number unique to all other entities in that application. This identifier number is valid for the duration of the exercise; however, entity identifier numbers may be reused when all possible numbers have been exhausted. No entity shall have an entity identifier number of NO_ENTITY, ALL_ENTITIES, or RQST_ASSIGN_ID. The entity iden- tifier number need not be registered or retained for future exercises. The entity identifier number shall be specified by a 16-bit unsigned integer. An entity identifier number equal to zero with valid site and application identification shall address a simulation application. An entity identifier number equal to ALL_ENTITIES shall mean all entities within the specified site and application. An entity identifier number equal to RQST_ASSIGN_ID allows the receiver of the create entity to define the entity identifier number of the new entity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + dis.EntityID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + }; + + dis.EntityID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + }; +}; // end of class + + // node.js module support +exports.EntityID = dis.EntityID; + +// End of EntityID class + +/** + * Section 5.3.3. Common superclass for EntityState, Collision, collision-elastic, and entity state update PDUs. This should be abstract. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityInformationFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityInformationFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityInformationFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityInformationFamilyPdu = dis.EntityInformationFamilyPdu; + +// End of EntityInformationFamilyPdu class + +/** + * Section 5.3.9. Common superclass for EntityManagment PDUs, including aggregate state, isGroupOf, TransferControLRequest, and isPartOf + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.EntityManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.EntityManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.EntityManagementFamilyPdu = dis.EntityManagementFamilyPdu; + +// End of EntityManagementFamilyPdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Unique ID for an entity that is tied to this state information */ + this.entityID = new dis.EntityID(); + + /** What force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the type of entity in the world */ + this.entityType = new dis.EntityType(); + + this.alternativeEntityType = new dis.EntityType(); + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** parameters used for dead reckoning */ + this.deadReckoningParameters = new dis.DeadReckoningParameter(); + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new dis.Marking(); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.EntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityType.initFromBinary(inputStream); + this.alternativeEntityType.initFromBinary(inputStream); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningParameters.initFromBinary(inputStream); + this.marking.initFromBinary(inputStream); + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + this.entityType.encodeToBinary(outputStream); + this.alternativeEntityType.encodeToBinary(outputStream); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + this.deadReckoningParameters.encodeToBinary(outputStream); + this.marking.encodeToBinary(outputStream); + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStatePdu = dis.EntityStatePdu; + +// End of EntityStatePdu class + +/** + * 5.3.3.4. Nonstatic information about a particular entity may be communicated by issuing an Entity State Update PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityStateUpdatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 67; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** This field shall identify the entity issuing the PDU */ + this.entityID = new dis.EntityID(); + + /** Padding */ + this.padding1 = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Describes the speed of the entity in the world */ + this.entityLinearVelocity = new dis.Vector3Float(); + + /** describes the location of the entity in the world */ + this.entityLocation = new dis.Vector3Double(); + + /** describes the orientation of the entity, in euler angles */ + this.entityOrientation = new dis.Orientation(); + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + this.articulationParameters = new Array(); + + dis.EntityStateUpdatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityID.initFromBinary(inputStream); + this.padding1 = inputStream.readByte(); + this.numberOfArticulationParameters = inputStream.readUByte(); + this.entityLinearVelocity.initFromBinary(inputStream); + this.entityLocation.initFromBinary(inputStream); + this.entityOrientation.initFromBinary(inputStream); + this.entityAppearance = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.EntityStateUpdatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityID.encodeToBinary(outputStream); + outputStream.writeByte(this.padding1); + outputStream.writeUByte(this.numberOfArticulationParameters); + this.entityLinearVelocity.encodeToBinary(outputStream); + this.entityLocation.encodeToBinary(outputStream); + this.entityOrientation.encodeToBinary(outputStream); + outputStream.writeInt(this.entityAppearance); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.EntityStateUpdatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.EntityStateUpdatePdu = dis.EntityStateUpdatePdu; + +// End of EntityStateUpdatePdu class + +/** + * Section 5.2.16. Identifies the type of entity, including kind of entity, domain (surface, subsurface, air, etc) country, category, etc. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Renamed from specific because that is a reserved word in SQL */ + this.spec = 0; + + this.extra = 0; + + dis.EntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.spec = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + }; + + dis.EntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.spec); + outputStream.writeUByte(this.extra); + }; +}; // end of class + + // node.js module support +exports.EntityType = dis.EntityType; + +// End of EntityType class + +/** + * Section 5.2.40. Information about a geometry, a state associated with a geometry, a bounding volume, or an associated entity ID. NOTE: this class requires hand coding. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Environment = function() +{ + /** Record type */ + this.environmentType = 0; + + /** length, in bits */ + this.length = 0; + + /** Identify the sequentially numbered record index */ + this.recordIndex = 0; + + /** padding */ + this.padding1 = 0; + + /** Geometry or state record */ + this.geometry = 0; + + /** padding to bring the total size up to a 64 bit boundry */ + this.padding2 = 0; + + dis.Environment.prototype.initFromBinary = function(inputStream) + { + this.environmentType = inputStream.readUInt(); + this.length = inputStream.readUByte(); + this.recordIndex = inputStream.readUByte(); + this.padding1 = inputStream.readUByte(); + this.geometry = inputStream.readUByte(); + this.padding2 = inputStream.readUByte(); + }; + + dis.Environment.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.environmentType); + outputStream.writeUByte(this.length); + outputStream.writeUByte(this.recordIndex); + outputStream.writeUByte(this.padding1); + outputStream.writeUByte(this.geometry); + outputStream.writeUByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.Environment = dis.Environment; + +// End of Environment class + +/** + * Section 5.3.11.1: Information about environmental effects and processes. This requires manual cleanup. the environmental record is variable, as is the padding. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EnvironmentalProcessPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 41; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Environmental process ID */ + this.environementalProcessID = new dis.EntityID(); + + /** Environment type */ + this.environmentType = new dis.EntityType(); + + /** model type */ + this.modelType = 0; + + /** Environment status */ + this.environmentStatus = 0; + + /** number of environment records */ + this.numberOfEnvironmentRecords = 0; + + /** PDU sequence number for the environmentla process if pdu sequencing required */ + this.sequenceNumber = 0; + + /** environemt records */ + this.environmentRecords = new Array(); + + dis.EnvironmentalProcessPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environementalProcessID.initFromBinary(inputStream); + this.environmentType.initFromBinary(inputStream); + this.modelType = inputStream.readUByte(); + this.environmentStatus = inputStream.readUByte(); + this.numberOfEnvironmentRecords = inputStream.readUByte(); + this.sequenceNumber = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfEnvironmentRecords; idx++) + { + var anX = new dis.Environment(); + anX.initFromBinary(inputStream); + this.environmentRecords.push(anX); + } + + }; + + dis.EnvironmentalProcessPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environementalProcessID.encodeToBinary(outputStream); + this.environmentType.encodeToBinary(outputStream); + outputStream.writeUByte(this.modelType); + outputStream.writeUByte(this.environmentStatus); + outputStream.writeUByte(this.numberOfEnvironmentRecords); + outputStream.writeUShort(this.sequenceNumber); + for(var idx = 0; idx < this.environmentRecords.length; idx++) + { + environmentRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EnvironmentalProcessPdu = dis.EnvironmentalProcessPdu; + +// End of EnvironmentalProcessPdu class + +/** + * Section 5.2.18. Identifies a unique event in a simulation via the combination of three values + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventID = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the number of the event */ + this.eventNumber = 0; + + dis.EventID.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.eventNumber = inputStream.readUShort(); + }; + + dis.EventID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.eventNumber); + }; +}; // end of class + + // node.js module support +exports.EventID = dis.EventID; + +// End of EventID class + +/** + * Section 5.3.6.11. Reports occurance of a significant event to the simulation manager. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 21; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Type of event */ + this.eventType = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.EventReportPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.EventReportPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.eventType); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportPdu = dis.EventReportPdu; + +// End of EventReportPdu class + +/** + * Section 5.3.12.11: reports the occurance of a significatnt event to the simulation manager. Needs manual intervention to fix padding in variable datums. UNFINISHED. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.EventReportReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 61; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** Event type */ + this.eventType = 0; + + /** padding */ + this.pad1 = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.EventReportReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.eventType = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.EventReportReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.pad1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.EventReportReliablePdu = dis.EventReportReliablePdu; + +// End of EventReportReliablePdu class + +/** + * Section 5.3.3.1. Represents the postion and state of one entity in the world. This is identical in function to entity state pdu, but generates less garbage to collect in the Java world. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FastEntityStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 1; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 1; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + /** the entity ID */ + this.entity = 0; + + /** what force this entity is affiliated with, eg red, blue, neutral, etc */ + this.forceId = 0; + + /** How many articulation parameters are in the variable length list */ + this.numberOfArticulationParameters = 0; + + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + /** specific info based on subcategory field. Name changed from specific because that is a reserved word in SQL. */ + this.specif = 0; + + this.extra = 0; + + /** Kind of entity */ + this.altEntityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.altDomain = 0; + + /** country to which the design of the entity is attributed */ + this.altCountry = 0; + + /** category of entity */ + this.altCategory = 0; + + /** subcategory of entity */ + this.altSubcategory = 0; + + /** specific info based on subcategory field */ + this.altSpecific = 0; + + this.altExtra = 0; + + /** X velo */ + this.xVelocity = 0; + + /** y Value */ + this.yVelocity = 0; + + /** Z value */ + this.zVelocity = 0; + + /** X value */ + this.xLocation = 0; + + /** y Value */ + this.yLocation = 0; + + /** Z value */ + this.zLocation = 0; + + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + /** a series of bit flags that are used to help draw the entity, such as smoking, on fire, etc. */ + this.entityAppearance = 0; + + /** enumeration of what dead reckoning algorighm to use */ + this.deadReckoningAlgorithm = 0; + + /** other parameters to use in the dead reckoning algorithm */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** X value */ + this.xAcceleration = 0; + + /** y Value */ + this.yAcceleration = 0; + + /** Z value */ + this.zAcceleration = 0; + + /** X value */ + this.xAngularVelocity = 0; + + /** y Value */ + this.yAngularVelocity = 0; + + /** Z value */ + this.zAngularVelocity = 0; + + /** characters that can be used for debugging, or to draw unique strings on the side of entities in the world */ + this.marking = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** a series of bit flags */ + this.capabilities = 0; + + /** variable length list of articulation parameters */ + this.articulationParameters = new Array(); + + dis.FastEntityStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + this.entity = inputStream.readUShort(); + this.forceId = inputStream.readUByte(); + this.numberOfArticulationParameters = inputStream.readByte(); + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + this.specif = inputStream.readUByte(); + this.extra = inputStream.readUByte(); + this.altEntityKind = inputStream.readUByte(); + this.altDomain = inputStream.readUByte(); + this.altCountry = inputStream.readUShort(); + this.altCategory = inputStream.readUByte(); + this.altSubcategory = inputStream.readUByte(); + this.altSpecific = inputStream.readUByte(); + this.altExtra = inputStream.readUByte(); + this.xVelocity = inputStream.readFloat32(); + this.yVelocity = inputStream.readFloat32(); + this.zVelocity = inputStream.readFloat32(); + this.xLocation = inputStream.readFloat64(); + this.yLocation = inputStream.readFloat64(); + this.zLocation = inputStream.readFloat64(); + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + this.entityAppearance = inputStream.readInt(); + this.deadReckoningAlgorithm = inputStream.readUByte(); + for(var idx = 0; idx < 15; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + this.xAcceleration = inputStream.readFloat32(); + this.yAcceleration = inputStream.readFloat32(); + this.zAcceleration = inputStream.readFloat32(); + this.xAngularVelocity = inputStream.readFloat32(); + this.yAngularVelocity = inputStream.readFloat32(); + this.zAngularVelocity = inputStream.readFloat32(); + for(var idx = 0; idx < 12; idx++) + { + this.marking[ idx ] = inputStream.readByte(); + } + this.capabilities = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfArticulationParameters; idx++) + { + var anX = new dis.ArticulationParameter(); + anX.initFromBinary(inputStream); + this.articulationParameters.push(anX); + } + + }; + + dis.FastEntityStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + outputStream.writeUShort(this.entity); + outputStream.writeUByte(this.forceId); + outputStream.writeByte(this.numberOfArticulationParameters); + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + outputStream.writeUByte(this.specif); + outputStream.writeUByte(this.extra); + outputStream.writeUByte(this.altEntityKind); + outputStream.writeUByte(this.altDomain); + outputStream.writeUShort(this.altCountry); + outputStream.writeUByte(this.altCategory); + outputStream.writeUByte(this.altSubcategory); + outputStream.writeUByte(this.altSpecific); + outputStream.writeUByte(this.altExtra); + outputStream.writeFloat32(this.xVelocity); + outputStream.writeFloat32(this.yVelocity); + outputStream.writeFloat32(this.zVelocity); + outputStream.writeFloat64(this.xLocation); + outputStream.writeFloat64(this.yLocation); + outputStream.writeFloat64(this.zLocation); + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + outputStream.writeInt(this.entityAppearance); + outputStream.writeUByte(this.deadReckoningAlgorithm); + for(var idx = 0; idx < 15; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + outputStream.writeFloat32(this.xAcceleration); + outputStream.writeFloat32(this.yAcceleration); + outputStream.writeFloat32(this.zAcceleration); + outputStream.writeFloat32(this.xAngularVelocity); + outputStream.writeFloat32(this.yAngularVelocity); + outputStream.writeFloat32(this.zAngularVelocity); + for(var idx = 0; idx < 12; idx++) + { + outputStream.writeByte(this.marking[ idx ] ); + } + outputStream.writeInt(this.capabilities); + for(var idx = 0; idx < this.articulationParameters.length; idx++) + { + articulationParameters[idx].encodeToBinary(outputStream); + } + + }; + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_paintScheme = function() +{ + var val = this.entityAppearance & 0x1; + return val >> 0; +}; + + +/** 0 uniform color, 1 camouflage */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_paintScheme= function(val) +{ + this.entityAppearance &= ~0x1; // Zero existing bits + val = val << 0; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_mobility = function() +{ + var val = this.entityAppearance & 0x2; + return val >> 1; +}; + + +/** 0 no mobility kill, 1 mobility kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_mobility= function(val) +{ + this.entityAppearance &= ~0x2; // Zero existing bits + val = val << 1; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_firepower = function() +{ + var val = this.entityAppearance & 0x4; + return val >> 2; +}; + + +/** 0 no firepower iill, 1 firepower kill */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_firepower= function(val) +{ + this.entityAppearance &= ~0x4; // Zero existing bits + val = val << 2; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_damage = function() +{ + var val = this.entityAppearance & 0x18; + return val >> 3; +}; + + +/** 0 no damage, 1 slight damage, 2 moderate, 3 destroyed */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_damage= function(val) +{ + this.entityAppearance &= ~0x18; // Zero existing bits + val = val << 3; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_smoke = function() +{ + var val = this.entityAppearance & 0x60; + return val >> 5; +}; + + +/** 0 no smoke, 1 smoke plume, 2 engine smoke, 3 engine smoke and plume */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_smoke= function(val) +{ + this.entityAppearance &= ~0x60; // Zero existing bits + val = val << 5; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_trailingEffects = function() +{ + var val = this.entityAppearance & 0x180; + return val >> 7; +}; + + +/** dust cloud, 0 none 1 small 2 medium 3 large */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_trailingEffects= function(val) +{ + this.entityAppearance &= ~0x180; // Zero existing bits + val = val << 7; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_hatch = function() +{ + var val = this.entityAppearance & 0xe00; + return val >> 9; +}; + + +/** 0 NA 1 closed popped 3 popped and person visible 4 open 5 open and person visible */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_hatch= function(val) +{ + this.entityAppearance &= ~0xe00; // Zero existing bits + val = val << 9; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_headlights = function() +{ + var val = this.entityAppearance & 0x1000; + return val >> 12; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_headlights= function(val) +{ + this.entityAppearance &= ~0x1000; // Zero existing bits + val = val << 12; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_tailLights = function() +{ + var val = this.entityAppearance & 0x2000; + return val >> 13; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_tailLights= function(val) +{ + this.entityAppearance &= ~0x2000; // Zero existing bits + val = val << 13; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_brakeLights = function() +{ + var val = this.entityAppearance & 0x4000; + return val >> 14; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_brakeLights= function(val) +{ + this.entityAppearance &= ~0x4000; // Zero existing bits + val = val << 14; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_flaming = function() +{ + var val = this.entityAppearance & 0x8000; + return val >> 15; +}; + + +/** 0 off 1 on */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_flaming= function(val) +{ + this.entityAppearance &= ~0x8000; // Zero existing bits + val = val << 15; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_launcher = function() +{ + var val = this.entityAppearance & 0x10000; + return val >> 16; +}; + + +/** 0 not raised 1 raised */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_launcher= function(val) +{ + this.entityAppearance &= ~0x10000; // Zero existing bits + val = val << 16; + this.entityAppearance = this.entityAppearance | val; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.getEntityAppearance_camouflageType = function() +{ + var val = this.entityAppearance & 0x60000; + return val >> 17; +}; + + +/** 0 desert 1 winter 2 forest 3 unused */ +dis.FastEntityStatePdu.prototype.setEntityAppearance_camouflageType= function(val) +{ + this.entityAppearance &= ~0x60000; // Zero existing bits + val = val << 17; + this.entityAppearance = this.entityAppearance | val; +}; + +}; // end of class + + // node.js module support +exports.FastEntityStatePdu = dis.FastEntityStatePdu; + +// End of FastEntityStatePdu class + +/** + * Sectioin 5.3.4.1. Information about someone firing something. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FirePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 2; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + /** ID of the munition that is being shot */ + this.munitionID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + this.fireMissionIndex = 0; + + /** location of the firing event */ + this.locationInWorldCoordinates = new dis.Vector3Double(); + + /** Describes munitions used in the firing event */ + this.burstDescriptor = new dis.BurstDescriptor(); + + /** Velocity of the ammunition */ + this.velocity = new dis.Vector3Float(); + + /** range to the target. Note the word range is a SQL reserved word. */ + this.rangeToTarget = 0; + + dis.FirePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + this.munitionID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.fireMissionIndex = inputStream.readInt(); + this.locationInWorldCoordinates.initFromBinary(inputStream); + this.burstDescriptor.initFromBinary(inputStream); + this.velocity.initFromBinary(inputStream); + this.rangeToTarget = inputStream.readFloat32(); + }; + + dis.FirePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + this.munitionID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeInt(this.fireMissionIndex); + this.locationInWorldCoordinates.encodeToBinary(outputStream); + this.burstDescriptor.encodeToBinary(outputStream); + this.velocity.encodeToBinary(outputStream); + outputStream.writeFloat32(this.rangeToTarget); + }; +}; // end of class + + // node.js module support +exports.FirePdu = dis.FirePdu; + +// End of FirePdu class + +/** + * Section 5.2.18. Fixed Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FixedDatum = function() +{ + /** ID of the fixed datum */ + this.fixedDatumID = 0; + + /** Value for the fixed datum */ + this.fixedDatumValue = 0; + + dis.FixedDatum.prototype.initFromBinary = function(inputStream) + { + this.fixedDatumID = inputStream.readUInt(); + this.fixedDatumValue = inputStream.readUInt(); + }; + + dis.FixedDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.fixedDatumID); + outputStream.writeUInt(this.fixedDatumValue); + }; +}; // end of class + + // node.js module support +exports.FixedDatum = dis.FixedDatum; + +// End of FixedDatum class + +/** + * 32 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FourByteChunk = function() +{ + /** four bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0); + + dis.FourByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 4; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.FourByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 4; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.FourByteChunk = dis.FourByteChunk; + +// End of FourByteChunk class + +/** + * Section 5.2.22. Contains electromagnetic emmision regineratin parameters that are variable throughout a scenario dependent on the actions of the participants in the simulation. Also provides basic parametric data that may be used to support low-fidelity simulations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterData = function() +{ + /** center frequency of the emission in hertz. */ + this.frequency = 0; + + /** Bandwidth of the frequencies corresponding to the fequency field. */ + this.frequencyRange = 0; + + /** Effective radiated power for the emission in DdBm. For a radar noise jammer, indicates the peak of the transmitted power. */ + this.effectiveRadiatedPower = 0; + + /** Average repetition frequency of the emission in hertz. */ + this.pulseRepetitionFrequency = 0; + + /** Average pulse width of the emission in microseconds. */ + this.pulseWidth = 0; + + /** Specifies the beam azimuth an elevation centers and corresponding half-angles to describe the scan volume */ + this.beamAzimuthCenter = 0; + + /** Specifies the beam azimuth sweep to determine scan volume */ + this.beamAzimuthSweep = 0; + + /** Specifies the beam elevation center to determine scan volume */ + this.beamElevationCenter = 0; + + /** Specifies the beam elevation sweep to determine scan volume */ + this.beamElevationSweep = 0; + + /** allows receiver to synchronize its regenerated scan pattern to that of the emmitter. Specifies the percentage of time a scan is through its pattern from its origion. */ + this.beamSweepSync = 0; + + dis.FundamentalParameterData.prototype.initFromBinary = function(inputStream) + { + this.frequency = inputStream.readFloat32(); + this.frequencyRange = inputStream.readFloat32(); + this.effectiveRadiatedPower = inputStream.readFloat32(); + this.pulseRepetitionFrequency = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.beamAzimuthCenter = inputStream.readFloat32(); + this.beamAzimuthSweep = inputStream.readFloat32(); + this.beamElevationCenter = inputStream.readFloat32(); + this.beamElevationSweep = inputStream.readFloat32(); + this.beamSweepSync = inputStream.readFloat32(); + }; + + dis.FundamentalParameterData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.frequencyRange); + outputStream.writeFloat32(this.effectiveRadiatedPower); + outputStream.writeFloat32(this.pulseRepetitionFrequency); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeFloat32(this.beamAzimuthCenter); + outputStream.writeFloat32(this.beamAzimuthSweep); + outputStream.writeFloat32(this.beamElevationCenter); + outputStream.writeFloat32(this.beamElevationSweep); + outputStream.writeFloat32(this.beamSweepSync); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterData = dis.FundamentalParameterData; + +// End of FundamentalParameterData class + +/** + * 5.2.45. Fundamental IFF atc data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.FundamentalParameterDataIff = function() +{ + /** ERP */ + this.erp = 0; + + /** frequency */ + this.frequency = 0; + + /** pgrf */ + this.pgrf = 0; + + /** Pulse width */ + this.pulseWidth = 0; + + /** Burst length */ + this.burstLength = 0; + + /** Applicable modes enumeration */ + this.applicableModes = 0; + + /** padding */ + this.pad2 = 0; + + /** padding */ + this.pad3 = 0; + + dis.FundamentalParameterDataIff.prototype.initFromBinary = function(inputStream) + { + this.erp = inputStream.readFloat32(); + this.frequency = inputStream.readFloat32(); + this.pgrf = inputStream.readFloat32(); + this.pulseWidth = inputStream.readFloat32(); + this.burstLength = inputStream.readUInt(); + this.applicableModes = inputStream.readUByte(); + this.pad2 = inputStream.readUShort(); + this.pad3 = inputStream.readUByte(); + }; + + dis.FundamentalParameterDataIff.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.erp); + outputStream.writeFloat32(this.frequency); + outputStream.writeFloat32(this.pgrf); + outputStream.writeFloat32(this.pulseWidth); + outputStream.writeUInt(this.burstLength); + outputStream.writeUByte(this.applicableModes); + outputStream.writeUShort(this.pad2); + outputStream.writeUByte(this.pad3); + }; +}; // end of class + + // node.js module support +exports.FundamentalParameterDataIff = dis.FundamentalParameterDataIff; + +// End of FundamentalParameterDataIff class + +/** + * 5.2.44: Grid data record, a common abstract superclass for several subtypes + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecord = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + dis.GridAxisRecord.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + }; + + dis.GridAxisRecord.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + }; +}; // end of class + + // node.js module support +exports.GridAxisRecord = dis.GridAxisRecord; + +// End of GridAxisRecord class + +/** + * 5.2.44: Grid data record, representation 0 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation0 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of bytes of environmental state data */ + this.numberOfBytes = 0; + + /** variable length variablelist of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation0.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfBytes = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfBytes; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation0.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfBytes); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation0 = dis.GridAxisRecordRepresentation0; + +// End of GridAxisRecordRepresentation0 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation1 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** constant scale factor */ + this.fieldScale = 0; + + /** constant offset used to scale grid data */ + this.fieldOffset = 0; + + /** Number of data values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation1.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.fieldScale = inputStream.readFloat32(); + this.fieldOffset = inputStream.readFloat32(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation1.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeFloat32(this.fieldScale); + outputStream.writeFloat32(this.fieldOffset); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation1 = dis.GridAxisRecordRepresentation1; + +// End of GridAxisRecordRepresentation1 class + +/** + * 5.2.44: Grid data record, representation 1 + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GridAxisRecordRepresentation2 = function() +{ + /** type of environmental sample */ + this.sampleType = 0; + + /** value that describes data representation */ + this.dataRepresentation = 0; + + /** number of values */ + this.numberOfValues = 0; + + /** variable length list of data parameters ^^^this is wrong--need padding as well */ + this.dataValues = new Array(); + + dis.GridAxisRecordRepresentation2.prototype.initFromBinary = function(inputStream) + { + this.sampleType = inputStream.readUShort(); + this.dataRepresentation = inputStream.readUShort(); + this.numberOfValues = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfValues; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.dataValues.push(anX); + } + + }; + + dis.GridAxisRecordRepresentation2.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.sampleType); + outputStream.writeUShort(this.dataRepresentation); + outputStream.writeUShort(this.numberOfValues); + for(var idx = 0; idx < this.dataValues.length; idx++) + { + dataValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GridAxisRecordRepresentation2 = dis.GridAxisRecordRepresentation2; + +// End of GridAxisRecordRepresentation2 class + +/** + * Section 5.3.11.2: Information about globat, spatially varying enviornmental effects. This requires manual cleanup; the grid axis records are variable sized. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.GriddedDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 42; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** environmental simulation application ID */ + this.environmentalSimulationApplicationID = new dis.EntityID(); + + /** unique identifier for each piece of enviornmental data */ + this.fieldNumber = 0; + + /** sequence number for the total set of PDUS used to transmit the data */ + this.pduNumber = 0; + + /** Total number of PDUS used to transmit the data */ + this.pduTotal = 0; + + /** coordinate system of the grid */ + this.coordinateSystem = 0; + + /** number of grid axes for the environmental data */ + this.numberOfGridAxes = 0; + + /** are domain grid axes identidal to those of the priveious domain update? */ + this.constantGrid = 0; + + /** type of environment */ + this.environmentType = new dis.EntityType(); + + /** orientation of the data grid */ + this.orientation = new dis.Orientation(); + + /** valid time of the enviormental data sample, 64 bit unsigned int */ + this.sampleTime = 0; + + /** total number of all data values for all pdus for an environmental sample */ + this.totalValues = 0; + + /** total number of data values at each grid point. */ + this.vectorDimension = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + /** Grid data ^^^This is wrong */ + this.gridDataList = new Array(); + + dis.GriddedDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.environmentalSimulationApplicationID.initFromBinary(inputStream); + this.fieldNumber = inputStream.readUShort(); + this.pduNumber = inputStream.readUShort(); + this.pduTotal = inputStream.readUShort(); + this.coordinateSystem = inputStream.readUShort(); + this.numberOfGridAxes = inputStream.readUByte(); + this.constantGrid = inputStream.readUByte(); + this.environmentType.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.sampleTime = inputStream.readLong(); + this.totalValues = inputStream.readUInt(); + this.vectorDimension = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.padding2 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfGridAxes; idx++) + { + var anX = new dis.GridAxisRecord(); + anX.initFromBinary(inputStream); + this.gridDataList.push(anX); + } + + }; + + dis.GriddedDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.environmentalSimulationApplicationID.encodeToBinary(outputStream); + outputStream.writeUShort(this.fieldNumber); + outputStream.writeUShort(this.pduNumber); + outputStream.writeUShort(this.pduTotal); + outputStream.writeUShort(this.coordinateSystem); + outputStream.writeUByte(this.numberOfGridAxes); + outputStream.writeUByte(this.constantGrid); + this.environmentType.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeLong(this.sampleTime); + outputStream.writeUInt(this.totalValues); + outputStream.writeUByte(this.vectorDimension); + outputStream.writeUShort(this.padding1); + outputStream.writeUByte(this.padding2); + for(var idx = 0; idx < this.gridDataList.length; idx++) + { + gridDataList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.GriddedDataPdu = dis.GriddedDataPdu; + +// End of GriddedDataPdu class + +/** + * 5.3.7.4.1: Navigational and IFF PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer1Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + dis.IffAtcNavAidsLayer1Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + }; + + dis.IffAtcNavAidsLayer1Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer1Pdu = dis.IffAtcNavAidsLayer1Pdu; + +// End of IffAtcNavAidsLayer1Pdu class + +/** + * Section 5.3.7.4.2 When present, layer 2 should follow layer 1 and have the following fields. This requires manual cleanup. the beamData attribute semantics are used in multiple ways. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffAtcNavAidsLayer2Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 28; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emissions */ + this.emittingEntityId = new dis.EntityID(); + + /** Number generated by the issuing simulation to associate realted events. */ + this.eventID = new dis.EventID(); + + /** Location wrt entity. There is some ambugiuity in the standard here, but this is the order it is listed in the table. */ + this.location = new dis.Vector3Float(); + + /** System ID information */ + this.systemID = new dis.SystemID(); + + /** padding */ + this.pad2 = 0; + + /** fundamental parameters */ + this.fundamentalParameters = new dis.IffFundamentalData(); + + /** layer header */ + this.layerHeader = new dis.LayerHeader(); + + /** beam data */ + this.beamData = new dis.BeamData(); + + /** Secondary operational data, 5.2.57 */ + this.secondaryOperationalData = new dis.BeamData(); + + /** variable length list of fundamental parameters. ^^^This is wrong */ + this.fundamentalIffParameters = new Array(); + + dis.IffAtcNavAidsLayer2Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityId.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.systemID.initFromBinary(inputStream); + this.pad2 = inputStream.readUShort(); + this.fundamentalParameters.initFromBinary(inputStream); + this.layerHeader.initFromBinary(inputStream); + this.beamData.initFromBinary(inputStream); + this.secondaryOperationalData.initFromBinary(inputStream); + for(var idx = 0; idx < this.pad2; idx++) + { + var anX = new dis.FundamentalParameterDataIff(); + anX.initFromBinary(inputStream); + this.fundamentalIffParameters.push(anX); + } + + }; + + dis.IffAtcNavAidsLayer2Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityId.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.systemID.encodeToBinary(outputStream); + outputStream.writeUShort(this.pad2); + this.fundamentalParameters.encodeToBinary(outputStream); + this.layerHeader.encodeToBinary(outputStream); + this.beamData.encodeToBinary(outputStream); + this.secondaryOperationalData.encodeToBinary(outputStream); + for(var idx = 0; idx < this.fundamentalIffParameters.length; idx++) + { + fundamentalIffParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IffAtcNavAidsLayer2Pdu = dis.IffAtcNavAidsLayer2Pdu; + +// End of IffAtcNavAidsLayer2Pdu class + +/** + * 5.2.42. Basic operational data ofr IFF ATC NAVAIDS + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IffFundamentalData = function() +{ + /** system status */ + this.systemStatus = 0; + + /** Alternate parameter 4 */ + this.alternateParameter4 = 0; + + /** eight boolean fields */ + this.informationLayers = 0; + + /** enumeration */ + this.modifier = 0; + + /** parameter, enumeration */ + this.parameter1 = 0; + + /** parameter, enumeration */ + this.parameter2 = 0; + + /** parameter, enumeration */ + this.parameter3 = 0; + + /** parameter, enumeration */ + this.parameter4 = 0; + + /** parameter, enumeration */ + this.parameter5 = 0; + + /** parameter, enumeration */ + this.parameter6 = 0; + + dis.IffFundamentalData.prototype.initFromBinary = function(inputStream) + { + this.systemStatus = inputStream.readUByte(); + this.alternateParameter4 = inputStream.readUByte(); + this.informationLayers = inputStream.readUByte(); + this.modifier = inputStream.readUByte(); + this.parameter1 = inputStream.readUShort(); + this.parameter2 = inputStream.readUShort(); + this.parameter3 = inputStream.readUShort(); + this.parameter4 = inputStream.readUShort(); + this.parameter5 = inputStream.readUShort(); + this.parameter6 = inputStream.readUShort(); + }; + + dis.IffFundamentalData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.systemStatus); + outputStream.writeUByte(this.alternateParameter4); + outputStream.writeUByte(this.informationLayers); + outputStream.writeUByte(this.modifier); + outputStream.writeUShort(this.parameter1); + outputStream.writeUShort(this.parameter2); + outputStream.writeUShort(this.parameter3); + outputStream.writeUShort(this.parameter4); + outputStream.writeUShort(this.parameter5); + outputStream.writeUShort(this.parameter6); + }; +}; // end of class + + // node.js module support +exports.IffFundamentalData = dis.IffFundamentalData; + +// End of IffFundamentalData class + +/** + * 5.2.46. Intercom communcations parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomCommunicationsParameters = function() +{ + /** Type of intercom parameters record */ + this.recordType = 0; + + /** length of record-specifid field, in octets */ + this.recordLength = 0; + + /** variable length variablelist of data parameters */ + this.parameterValues = new Array(); + + dis.IntercomCommunicationsParameters.prototype.initFromBinary = function(inputStream) + { + this.recordType = inputStream.readUShort(); + this.recordLength = inputStream.readUShort(); + for(var idx = 0; idx < this.recordLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.parameterValues.push(anX); + } + + }; + + dis.IntercomCommunicationsParameters.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.recordType); + outputStream.writeUShort(this.recordLength); + for(var idx = 0; idx < this.parameterValues.length; idx++) + { + parameterValues[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomCommunicationsParameters = dis.IntercomCommunicationsParameters; + +// End of IntercomCommunicationsParameters class + +/** + * Section 5.3.8.5. Detailed inofrmation about the state of an intercom device and the actions it is requestion of another intercom device, or the response to a requested action. Required manual intervention to fix the intercom parameters, which can be of varialbe length. UNFINSISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomControlPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 32; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** control type */ + this.controlType = 0; + + /** control type */ + this.communicationsChannelType = 0; + + /** Source entity ID */ + this.sourceEntityID = new dis.EntityID(); + + /** The specific intercom device being simulated within an entity. */ + this.sourceCommunicationsDeviceID = 0; + + /** Line number to which the intercom control refers */ + this.sourceLineID = 0; + + /** priority of this message relative to transmissons from other intercom devices */ + this.transmitPriority = 0; + + /** current transmit state of the line */ + this.transmitLineState = 0; + + /** detailed type requested. */ + this.command = 0; + + /** eid of the entity that has created this intercom channel. */ + this.masterEntityID = new dis.EntityID(); + + /** specific intercom device that has created this intercom channel */ + this.masterCommunicationsDeviceID = 0; + + /** number of intercom parameters */ + this.intercomParametersLength = 0; + + /** Must be */ + this.intercomParameters = new Array(); + + dis.IntercomControlPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.controlType = inputStream.readUByte(); + this.communicationsChannelType = inputStream.readUByte(); + this.sourceEntityID.initFromBinary(inputStream); + this.sourceCommunicationsDeviceID = inputStream.readUByte(); + this.sourceLineID = inputStream.readUByte(); + this.transmitPriority = inputStream.readUByte(); + this.transmitLineState = inputStream.readUByte(); + this.command = inputStream.readUByte(); + this.masterEntityID.initFromBinary(inputStream); + this.masterCommunicationsDeviceID = inputStream.readUShort(); + this.intercomParametersLength = inputStream.readUInt(); + for(var idx = 0; idx < this.intercomParametersLength; idx++) + { + var anX = new dis.IntercomCommunicationsParameters(); + anX.initFromBinary(inputStream); + this.intercomParameters.push(anX); + } + + }; + + dis.IntercomControlPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + outputStream.writeUByte(this.controlType); + outputStream.writeUByte(this.communicationsChannelType); + this.sourceEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.sourceCommunicationsDeviceID); + outputStream.writeUByte(this.sourceLineID); + outputStream.writeUByte(this.transmitPriority); + outputStream.writeUByte(this.transmitLineState); + outputStream.writeUByte(this.command); + this.masterEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.masterCommunicationsDeviceID); + outputStream.writeUInt(this.intercomParametersLength); + for(var idx = 0; idx < this.intercomParameters.length; idx++) + { + intercomParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomControlPdu = dis.IntercomControlPdu; + +// End of IntercomControlPdu class + +/** + * Section 5.3.8.4. Actual transmission of intercome voice data. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IntercomSignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 31; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entitythat is the source of the communication */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.communicationsDeviceID = 0; + + /** encoding scheme */ + this.encodingScheme = 0; + + /** tactical data link type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** data length, in bits */ + this.dataLength = 0; + + /** samples */ + this.samples = 0; + + /** data bytes */ + this.data = new Array(); + + dis.IntercomSignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.communicationsDeviceID = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.IntercomSignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.communicationsDeviceID); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IntercomSignalPdu = dis.IntercomSignalPdu; + +// End of IntercomSignalPdu class + +/** + * Section 5.3.9.2 Information about a particular group of entities grouped together for the purposes of netowrk bandwidth reduction or aggregation. Needs manual cleanup. The GED size requires a database lookup. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsGroupOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 34; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of aggregated entities */ + this.groupEntityID = new dis.EntityID(); + + /** type of entities constituting the group */ + this.groupedEntityCategory = 0; + + /** Number of individual entities constituting the group */ + this.numberOfGroupedEntities = 0; + + /** padding */ + this.pad2 = 0; + + /** latitude */ + this.latitude = 0; + + /** longitude */ + this.longitude = 0; + + /** GED records about each individual entity in the group. ^^^this is wrong--need a database lookup to find the actual size of the list elements */ + this.groupedEntityDescriptions = new Array(); + + dis.IsGroupOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.groupEntityID.initFromBinary(inputStream); + this.groupedEntityCategory = inputStream.readUByte(); + this.numberOfGroupedEntities = inputStream.readUByte(); + this.pad2 = inputStream.readUInt(); + this.latitude = inputStream.readFloat64(); + this.longitude = inputStream.readFloat64(); + for(var idx = 0; idx < this.numberOfGroupedEntities; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.groupedEntityDescriptions.push(anX); + } + + }; + + dis.IsGroupOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.groupEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.groupedEntityCategory); + outputStream.writeUByte(this.numberOfGroupedEntities); + outputStream.writeUInt(this.pad2); + outputStream.writeFloat64(this.latitude); + outputStream.writeFloat64(this.longitude); + for(var idx = 0; idx < this.groupedEntityDescriptions.length; idx++) + { + groupedEntityDescriptions[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.IsGroupOfPdu = dis.IsGroupOfPdu; + +// End of IsGroupOfPdu class + +/** + * Section 5.3.9.4 The joining of two or more simulation entities is communicated by this PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.IsPartOfPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 36; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating PDU */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving PDU */ + this.receivingEntityID = new dis.EntityID(); + + /** relationship of joined parts */ + this.relationship = new dis.Relationship(); + + /** location of part; centroid of part in host's coordinate system. x=range, y=bearing, z=0 */ + this.partLocation = new dis.Vector3Float(); + + /** named location */ + this.namedLocationID = new dis.NamedLocation(); + + /** entity type */ + this.partEntityType = new dis.EntityType(); + + dis.IsPartOfPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.relationship.initFromBinary(inputStream); + this.partLocation.initFromBinary(inputStream); + this.namedLocationID.initFromBinary(inputStream); + this.partEntityType.initFromBinary(inputStream); + }; + + dis.IsPartOfPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.relationship.encodeToBinary(outputStream); + this.partLocation.encodeToBinary(outputStream); + this.namedLocationID.encodeToBinary(outputStream); + this.partEntityType.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.IsPartOfPdu = dis.IsPartOfPdu; + +// End of IsPartOfPdu class + +/** + * 5.2.47. Layer header. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LayerHeader = function() +{ + /** Layer number */ + this.layerNumber = 0; + + /** Layer speccific information enumeration */ + this.layerSpecificInformaiton = 0; + + /** information length */ + this.length = 0; + + dis.LayerHeader.prototype.initFromBinary = function(inputStream) + { + this.layerNumber = inputStream.readUByte(); + this.layerSpecificInformaiton = inputStream.readUByte(); + this.length = inputStream.readUShort(); + }; + + dis.LayerHeader.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.layerNumber); + outputStream.writeUByte(this.layerSpecificInformaiton); + outputStream.writeUShort(this.length); + }; +}; // end of class + + // node.js module support +exports.LayerHeader = dis.LayerHeader; + +// End of LayerHeader class + +/** + * Section 5.3.11.4: Information abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point and has size or orientation. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 44; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** number of linear segment parameters */ + this.numberOfSegments = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Linear segment parameters */ + this.linearSegmentParameters = new Array(); + + dis.LinearObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfSegments = inputStream.readUByte(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.objectType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSegments; idx++) + { + var anX = new dis.LinearSegmentParameter(); + anX.initFromBinary(inputStream); + this.linearSegmentParameters.push(anX); + } + + }; + + dis.LinearObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfSegments); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + this.objectType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.linearSegmentParameters.length; idx++) + { + linearSegmentParameters[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.LinearObjectStatePdu = dis.LinearObjectStatePdu; + +// End of LinearObjectStatePdu class + +/** + * 5.2.48: Linear segment parameters + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LinearSegmentParameter = function() +{ + /** number of segments */ + this.segmentNumber = 0; + + /** segment appearance */ + this.segmentAppearance = new dis.SixByteChunk(); + + /** location */ + this.location = new dis.Vector3Double(); + + /** orientation */ + this.orientation = new dis.Orientation(); + + /** segmentLength */ + this.segmentLength = 0; + + /** segmentWidth */ + this.segmentWidth = 0; + + /** segmentHeight */ + this.segmentHeight = 0; + + /** segment Depth */ + this.segmentDepth = 0; + + /** segment Depth */ + this.pad1 = 0; + + dis.LinearSegmentParameter.prototype.initFromBinary = function(inputStream) + { + this.segmentNumber = inputStream.readUByte(); + this.segmentAppearance.initFromBinary(inputStream); + this.location.initFromBinary(inputStream); + this.orientation.initFromBinary(inputStream); + this.segmentLength = inputStream.readUShort(); + this.segmentWidth = inputStream.readUShort(); + this.segmentHeight = inputStream.readUShort(); + this.segmentDepth = inputStream.readUShort(); + this.pad1 = inputStream.readUInt(); + }; + + dis.LinearSegmentParameter.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.segmentNumber); + this.segmentAppearance.encodeToBinary(outputStream); + this.location.encodeToBinary(outputStream); + this.orientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.segmentLength); + outputStream.writeUShort(this.segmentWidth); + outputStream.writeUShort(this.segmentHeight); + outputStream.writeUShort(this.segmentDepth); + outputStream.writeUInt(this.pad1); + }; +}; // end of class + + // node.js module support +exports.LinearSegmentParameter = dis.LinearSegmentParameter; + +// End of LinearSegmentParameter class + +/** + * Section 5.3.5. Abstract superclass for logistics PDUs. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.LogisticsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.LogisticsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.LogisticsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.LogisticsFamilyPdu = dis.LogisticsFamilyPdu; + +// End of LogisticsFamilyPdu class + +/** + * Section 5.2.15. Specifies the character set used inthe first byte, followed by 11 characters of text data. + * The generated Marking class should be augmented with a patch that adds getMarking() and + * setMarking() methods that convert between arrays and strings, and clamp the length + * of the string to 11 characters. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Marking = function() +{ + /** The character set */ + this.characterSet = 0; + + /** The characters */ + this.characters = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + dis.Marking.prototype.initFromBinary = function(inputStream) + { + this.characterSet = inputStream.readUByte(); + for(var idx = 0; idx < 11; idx++) + { + this.characters[ idx ] = inputStream.readByte(); + } + }; + + dis.Marking.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.characterSet); + for(var idx = 0; idx < 11; idx++) + { + outputStream.writeByte(this.characters[ idx ] ); + } + }; + + /* + * Returns the byte array marking, in string format. + * @return string format marking characters + */ + dis.Marking.prototype.getMarking = function() + { + var marking = ""; + for(var idx = 0; idx < 11; idx++) + { + marking = marking + String.fromCharCode(this.characters[idx]); + } + + return marking; + }; + + /** + * Given a string format marking, sets the bytes of the marking object + * to the appropriate character values. Clamps the string to no more + * than 11 characters. + * + * @param {String} newMarking string format marking + * @returns {nothing} + */ + dis.Marking.prototype.setMarking = function(newMarking) + { + var stringLen = newMarking.length; + if(stringLen > 11) + stringLen = 11; + + // Copy over up to 11 characters from the string to the array + var charsCopied = 0; + while(charsCopied < stringLen) + { + this.characters[charsCopied] = newMarking.charCodeAt( charsCopied ); + charsCopied++; + } + + // Zero-fill the remainer of the character array + while(charsCopied < 11) + { + this.characters[ charsCopied ] = 0; + charsCopied++; + } + + }; +}; // end of class + + // node.js module support +exports.Marking = dis.Marking; + +// End of Marking class + +/** + * Section 5.3.10.3 Information about individual mines within a minefield. This is very, very wrong. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 39; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** ID of entity making request */ + this.requestingEntityID = new dis.EntityID(); + + /** Minefield sequence number */ + this.minefieldSequenceNumbeer = 0; + + /** request ID */ + this.requestID = 0; + + /** pdu sequence number */ + this.pduSequenceNumber = 0; + + /** number of pdus in response */ + this.numberOfPdus = 0; + + /** how many mines are in this PDU */ + this.numberOfMinesInThisPdu = 0; + + /** how many sensor type are in this PDU */ + this.numberOfSensorTypes = 0; + + /** padding */ + this.pad2 = 0; + + /** 32 boolean fields */ + this.dataFilter = 0; + + /** Mine type */ + this.mineType = new dis.EntityType(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + /** Padding to get things 32-bit aligned. ^^^this is wrong--dyanmically sized padding needed */ + this.pad3 = 0; + + /** Mine locations */ + this.mineLocation = new Array(); + + dis.MinefieldDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.minefieldSequenceNumbeer = inputStream.readUShort(); + this.requestID = inputStream.readUByte(); + this.pduSequenceNumber = inputStream.readUByte(); + this.numberOfPdus = inputStream.readUByte(); + this.numberOfMinesInThisPdu = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.mineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + this.pad3 = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMinesInThisPdu; idx++) + { + var anX = new dis.Vector3Float(); + anX.initFromBinary(inputStream); + this.mineLocation.push(anX); + } + + }; + + dis.MinefieldDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequenceNumbeer); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.pduSequenceNumber); + outputStream.writeUByte(this.numberOfPdus); + outputStream.writeUByte(this.numberOfMinesInThisPdu); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.dataFilter); + this.mineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + outputStream.writeUByte(this.pad3); + for(var idx = 0; idx < this.mineLocation.length; idx++) + { + mineLocation[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldDataPdu = dis.MinefieldDataPdu; + +// End of MinefieldDataPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.MinefieldFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.MinefieldFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.MinefieldFamilyPdu = dis.MinefieldFamilyPdu; + +// End of MinefieldFamilyPdu class + +/** + * Section 5.3.10.2 Query a minefield for information about individual mines. Requires manual clean up to get the padding right. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldQueryPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 38; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** EID of entity making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** Number of perimeter points for the minefield */ + this.numberOfPerimeterPoints = 0; + + /** Padding */ + this.pad2 = 0; + + /** Number of sensor types */ + this.numberOfSensorTypes = 0; + + /** data filter, 32 boolean fields */ + this.dataFilter = 0; + + /** Entity type of mine being requested */ + this.requestedMineType = new dis.EntityType(); + + /** perimeter points of request */ + this.requestedPerimeterPoints = new Array(); + + /** Sensor types, each 16 bits long */ + this.sensorTypes = new Array(); + + dis.MinefieldQueryPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.pad2 = inputStream.readUByte(); + this.numberOfSensorTypes = inputStream.readUByte(); + this.dataFilter = inputStream.readUInt(); + this.requestedMineType.initFromBinary(inputStream); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.requestedPerimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfSensorTypes; idx++) + { + var anX = new dis.TwoByteChunk(); + anX.initFromBinary(inputStream); + this.sensorTypes.push(anX); + } + + }; + + dis.MinefieldQueryPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + outputStream.writeUByte(this.pad2); + outputStream.writeUByte(this.numberOfSensorTypes); + outputStream.writeUInt(this.dataFilter); + this.requestedMineType.encodeToBinary(outputStream); + for(var idx = 0; idx < this.requestedPerimeterPoints.length; idx++) + { + requestedPerimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.sensorTypes.length; idx++) + { + sensorTypes[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldQueryPdu = dis.MinefieldQueryPdu; + +// End of MinefieldQueryPdu class + +/** + * Section 5.3.10.4 proivde the means to request a retransmit of a minefield data pdu. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldResponseNackPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 40; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** entity ID making the request */ + this.requestingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** how many pdus were missing */ + this.numberOfMissingPdus = 0; + + /** PDU sequence numbers that were missing */ + this.missingPduSequenceNumbers = new Array(); + + dis.MinefieldResponseNackPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.requestingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUByte(); + this.numberOfMissingPdus = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfMissingPdus; idx++) + { + var anX = new dis.EightByteChunk(); + anX.initFromBinary(inputStream); + this.missingPduSequenceNumbers.push(anX); + } + + }; + + dis.MinefieldResponseNackPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + this.requestingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requestID); + outputStream.writeUByte(this.numberOfMissingPdus); + for(var idx = 0; idx < this.missingPduSequenceNumbers.length; idx++) + { + missingPduSequenceNumbers[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldResponseNackPdu = dis.MinefieldResponseNackPdu; + +// End of MinefieldResponseNackPdu class + +/** + * Section 5.3.10.1 Abstract superclass for PDUs relating to minefields. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.MinefieldStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 37; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 8; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Minefield ID */ + this.minefieldID = new dis.EntityID(); + + /** Minefield sequence */ + this.minefieldSequence = 0; + + /** force ID */ + this.forceID = 0; + + /** Number of permieter points */ + this.numberOfPerimeterPoints = 0; + + /** type of minefield */ + this.minefieldType = new dis.EntityType(); + + /** how many mine types */ + this.numberOfMineTypes = 0; + + /** location of minefield in world coords */ + this.minefieldLocation = new dis.Vector3Double(); + + /** orientation of minefield */ + this.minefieldOrientation = new dis.Orientation(); + + /** appearance bitflags */ + this.appearance = 0; + + /** protocolMode */ + this.protocolMode = 0; + + /** perimeter points for the minefield */ + this.perimeterPoints = new Array(); + + /** Type of mines */ + this.mineType = new Array(); + + dis.MinefieldStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.minefieldID.initFromBinary(inputStream); + this.minefieldSequence = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.numberOfPerimeterPoints = inputStream.readUByte(); + this.minefieldType.initFromBinary(inputStream); + this.numberOfMineTypes = inputStream.readUShort(); + this.minefieldLocation.initFromBinary(inputStream); + this.minefieldOrientation.initFromBinary(inputStream); + this.appearance = inputStream.readUShort(); + this.protocolMode = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPerimeterPoints; idx++) + { + var anX = new dis.Point(); + anX.initFromBinary(inputStream); + this.perimeterPoints.push(anX); + } + + for(var idx = 0; idx < this.numberOfMineTypes; idx++) + { + var anX = new dis.EntityType(); + anX.initFromBinary(inputStream); + this.mineType.push(anX); + } + + }; + + dis.MinefieldStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.minefieldID.encodeToBinary(outputStream); + outputStream.writeUShort(this.minefieldSequence); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.numberOfPerimeterPoints); + this.minefieldType.encodeToBinary(outputStream); + outputStream.writeUShort(this.numberOfMineTypes); + this.minefieldLocation.encodeToBinary(outputStream); + this.minefieldOrientation.encodeToBinary(outputStream); + outputStream.writeUShort(this.appearance); + outputStream.writeUShort(this.protocolMode); + for(var idx = 0; idx < this.perimeterPoints.length; idx++) + { + perimeterPoints[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.mineType.length; idx++) + { + mineType[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.MinefieldStatePdu = dis.MinefieldStatePdu; + +// End of MinefieldStatePdu class + +/** + * Radio modulation + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ModulationType = function() +{ + /** spread spectrum, 16 bit boolean array */ + this.spreadSpectrum = 0; + + /** major */ + this.major = 0; + + /** detail */ + this.detail = 0; + + /** system */ + this.system = 0; + + dis.ModulationType.prototype.initFromBinary = function(inputStream) + { + this.spreadSpectrum = inputStream.readUShort(); + this.major = inputStream.readUShort(); + this.detail = inputStream.readUShort(); + this.system = inputStream.readUShort(); + }; + + dis.ModulationType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.spreadSpectrum); + outputStream.writeUShort(this.major); + outputStream.writeUShort(this.detail); + outputStream.writeUShort(this.system); + }; +}; // end of class + + // node.js module support +exports.ModulationType = dis.ModulationType; + +// End of ModulationType class + +/** + * discrete ostional relationsihip + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.NamedLocation = function() +{ + /** station name enumeration */ + this.stationName = 0; + + /** station number */ + this.stationNumber = 0; + + dis.NamedLocation.prototype.initFromBinary = function(inputStream) + { + this.stationName = inputStream.readUShort(); + this.stationNumber = inputStream.readUShort(); + }; + + dis.NamedLocation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.stationName); + outputStream.writeUShort(this.stationNumber); + }; +}; // end of class + + // node.js module support +exports.NamedLocation = dis.NamedLocation; + +// End of NamedLocation class + +/** + * Identifies type of object. This is a shorter version of EntityType that omits the specific and extra fields. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ObjectType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** subcategory of entity */ + this.subcategory = 0; + + dis.ObjectType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.subcategory = inputStream.readUByte(); + }; + + dis.ObjectType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.subcategory); + }; +}; // end of class + + // node.js module support +exports.ObjectType = dis.ObjectType; + +// End of ObjectType class + +/** + * 8 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.OneByteChunk = function() +{ + /** one byte of arbitrary data */ + this.otherParameters = new Array(0); + + dis.OneByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 1; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.OneByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 1; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.OneByteChunk = dis.OneByteChunk; + +// End of OneByteChunk class + +/** + * Section 5.2.17. Three floating point values representing an orientation, psi, theta, and phi, aka the euler angles, in radians + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Orientation = function() +{ + this.psi = 0; + + this.theta = 0; + + this.phi = 0; + + dis.Orientation.prototype.initFromBinary = function(inputStream) + { + this.psi = inputStream.readFloat32(); + this.theta = inputStream.readFloat32(); + this.phi = inputStream.readFloat32(); + }; + + dis.Orientation.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.psi); + outputStream.writeFloat32(this.theta); + outputStream.writeFloat32(this.phi); + }; +}; // end of class + + // node.js module support +exports.Orientation = dis.Orientation; + +// End of Orientation class + +/** + * The superclass for all PDUs. This incorporates the PduHeader record, section 5.2.29. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Pdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 0; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.Pdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.Pdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.Pdu = dis.Pdu; + +// End of Pdu class + +/** + * A container that holds PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduContainer = function() +{ + /** Number of PDUs in the container list */ + this.numberOfPdus = 0; + + /** List of PDUs */ + this.pdus = new Array(); + + dis.PduContainer.prototype.initFromBinary = function(inputStream) + { + this.numberOfPdus = inputStream.readInt(); + for(var idx = 0; idx < this.numberOfPdus; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdus.push(anX); + } + + }; + + dis.PduContainer.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeInt(this.numberOfPdus); + for(var idx = 0; idx < this.pdus.length; idx++) + { + pdus[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduContainer = dis.PduContainer; + +// End of PduContainer class + +/** + * Non-DIS class, used to describe streams of PDUs when logging to SQL databases + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PduStream = function() +{ + /** short description of this PDU stream */ + this.shortDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Longish description of this PDU stream */ + this.longDescription = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Name of person performing recording */ + this.personRecording = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Email of person performing recording */ + this.authorEmail = new Array(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0); + + /** Start time of recording, in Unix time */ + this.startTime = 0; + + /** stop time of recording, in Unix time */ + this.stopTime = 0; + + /** how many PDUs in this stream */ + this.pduCount = 0; + + /** variable length list of PDUs */ + this.pdusInStream = new Array(); + + dis.PduStream.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 256; idx++) + { + this.shortDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 512; idx++) + { + this.longDescription[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.personRecording[ idx ] = inputStream.readByte(); + } + for(var idx = 0; idx < 128; idx++) + { + this.authorEmail[ idx ] = inputStream.readByte(); + } + this.startTime = inputStream.readLong(); + this.stopTime = inputStream.readLong(); + this.pduCount = inputStream.readUInt(); + for(var idx = 0; idx < this.pduCount; idx++) + { + var anX = new dis.Pdu(); + anX.initFromBinary(inputStream); + this.pdusInStream.push(anX); + } + + }; + + dis.PduStream.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 256; idx++) + { + outputStream.writeByte(this.shortDescription[ idx ] ); + } + for(var idx = 0; idx < 512; idx++) + { + outputStream.writeByte(this.longDescription[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.personRecording[ idx ] ); + } + for(var idx = 0; idx < 128; idx++) + { + outputStream.writeByte(this.authorEmail[ idx ] ); + } + outputStream.writeLong(this.startTime); + outputStream.writeLong(this.stopTime); + outputStream.writeUInt(this.pduCount); + for(var idx = 0; idx < this.pdusInStream.length; idx++) + { + pdusInStream[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.PduStream = dis.PduStream; + +// End of PduStream class + +/** + * x,y point + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Point = function() +{ + /** x */ + this.x = 0; + + /** y */ + this.y = 0; + + dis.Point.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + }; + + dis.Point.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + }; +}; // end of class + + // node.js module support +exports.Point = dis.Point; + +// End of Point class + +/** + * Section 5.3.11.3: Inormation abut the addition or modification of a synthecic enviroment object that is anchored to the terrain with a single point. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PointObjectStatePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 43; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object in synthetic environment */ + this.objectID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.referencedObjectID = new dis.EntityID(); + + /** unique update number of each state transition of an object */ + this.updateNumber = 0; + + /** force ID */ + this.forceID = 0; + + /** modifications */ + this.modifications = 0; + + /** Object type */ + this.objectType = new dis.ObjectType(); + + /** Object location */ + this.objectLocation = new dis.Vector3Double(); + + /** Object orientation */ + this.objectOrientation = new dis.Orientation(); + + /** Object apperance */ + this.objectAppearance = 0; + + /** requesterID */ + this.requesterID = new dis.SimulationAddress(); + + /** receiver ID */ + this.receivingID = new dis.SimulationAddress(); + + /** padding */ + this.pad2 = 0; + + dis.PointObjectStatePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.objectID.initFromBinary(inputStream); + this.referencedObjectID.initFromBinary(inputStream); + this.updateNumber = inputStream.readUShort(); + this.forceID = inputStream.readUByte(); + this.modifications = inputStream.readUByte(); + this.objectType.initFromBinary(inputStream); + this.objectLocation.initFromBinary(inputStream); + this.objectOrientation.initFromBinary(inputStream); + this.objectAppearance = inputStream.readFloat64(); + this.requesterID.initFromBinary(inputStream); + this.receivingID.initFromBinary(inputStream); + this.pad2 = inputStream.readUInt(); + }; + + dis.PointObjectStatePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.objectID.encodeToBinary(outputStream); + this.referencedObjectID.encodeToBinary(outputStream); + outputStream.writeUShort(this.updateNumber); + outputStream.writeUByte(this.forceID); + outputStream.writeUByte(this.modifications); + this.objectType.encodeToBinary(outputStream); + this.objectLocation.encodeToBinary(outputStream); + this.objectOrientation.encodeToBinary(outputStream); + outputStream.writeFloat64(this.objectAppearance); + this.requesterID.encodeToBinary(outputStream); + this.receivingID.encodeToBinary(outputStream); + outputStream.writeUInt(this.pad2); + }; +}; // end of class + + // node.js module support +exports.PointObjectStatePdu = dis.PointObjectStatePdu; + +// End of PointObjectStatePdu class + +/** + * Data about a propulsion system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.PropulsionSystemData = function() +{ + /** powerSetting */ + this.powerSetting = 0; + + /** engine RPMs */ + this.engineRpm = 0; + + dis.PropulsionSystemData.prototype.initFromBinary = function(inputStream) + { + this.powerSetting = inputStream.readFloat32(); + this.engineRpm = inputStream.readFloat32(); + }; + + dis.PropulsionSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.powerSetting); + outputStream.writeFloat32(this.engineRpm); + }; +}; // end of class + + // node.js module support +exports.PropulsionSystemData = dis.PropulsionSystemData; + +// End of PropulsionSystemData class + +/** + * Section 5.3.8. Abstract superclass for radio communications PDUs. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioCommunicationsFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.RadioCommunicationsFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.RadioCommunicationsFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.RadioCommunicationsFamilyPdu = dis.RadioCommunicationsFamilyPdu; + +// End of RadioCommunicationsFamilyPdu class + +/** + * Section 5.2.25. Identifies the type of radio + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RadioEntityType = function() +{ + /** Kind of entity */ + this.entityKind = 0; + + /** Domain of entity (air, surface, subsurface, space, etc) */ + this.domain = 0; + + /** country to which the design of the entity is attributed */ + this.country = 0; + + /** category of entity */ + this.category = 0; + + /** specific info based on subcategory field */ + this.nomenclatureVersion = 0; + + this.nomenclature = 0; + + dis.RadioEntityType.prototype.initFromBinary = function(inputStream) + { + this.entityKind = inputStream.readUByte(); + this.domain = inputStream.readUByte(); + this.country = inputStream.readUShort(); + this.category = inputStream.readUByte(); + this.nomenclatureVersion = inputStream.readUByte(); + this.nomenclature = inputStream.readUShort(); + }; + + dis.RadioEntityType.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.entityKind); + outputStream.writeUByte(this.domain); + outputStream.writeUShort(this.country); + outputStream.writeUByte(this.category); + outputStream.writeUByte(this.nomenclatureVersion); + outputStream.writeUShort(this.nomenclature); + }; +}; // end of class + + // node.js module support +exports.RadioEntityType = dis.RadioEntityType; + +// End of RadioEntityType class + +/** + * Section 5.3.8.3. Communication of a receiver state. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ReceiverPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 27; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.receiverState = 0; + + /** padding */ + this.padding1 = 0; + + /** received power */ + this.receivedPower = 0; + + /** ID of transmitter */ + this.transmitterEntityId = new dis.EntityID(); + + /** ID of transmitting radio */ + this.transmitterRadioId = 0; + + dis.ReceiverPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.receiverState = inputStream.readUShort(); + this.padding1 = inputStream.readUShort(); + this.receivedPower = inputStream.readFloat32(); + this.transmitterEntityId.initFromBinary(inputStream); + this.transmitterRadioId = inputStream.readUShort(); + }; + + dis.ReceiverPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.receiverState); + outputStream.writeUShort(this.padding1); + outputStream.writeFloat32(this.receivedPower); + this.transmitterEntityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.transmitterRadioId); + }; +}; // end of class + + // node.js module support +exports.ReceiverPdu = dis.ReceiverPdu; + +// End of ReceiverPdu class + +/** + * Section 5.3.12.13: A request for one or more records of data from an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordQueryReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 65; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** event type */ + this.eventType = 0; + + /** time */ + this.time = 0; + + /** numberOfRecords */ + this.numberOfRecords = 0; + + /** record IDs */ + this.recordIDs = new Array(); + + dis.RecordQueryReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.eventType = inputStream.readUShort(); + this.time = inputStream.readUInt(); + this.numberOfRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecords; idx++) + { + var anX = new dis.FourByteChunk(); + anX.initFromBinary(inputStream); + this.recordIDs.push(anX); + } + + }; + + dis.RecordQueryReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUShort(this.eventType); + outputStream.writeUInt(this.time); + outputStream.writeUInt(this.numberOfRecords); + for(var idx = 0; idx < this.recordIDs.length; idx++) + { + recordIDs[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.RecordQueryReliablePdu = dis.RecordQueryReliablePdu; + +// End of RecordQueryReliablePdu class + +/** + * Record sets, used in transfer control request PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RecordSet = function() +{ + /** record ID */ + this.recordID = 0; + + /** record set serial number */ + this.recordSetSerialNumber = 0; + + /** record length */ + this.recordLength = 0; + + /** record count */ + this.recordCount = 0; + + /** ^^^This is wrong--variable sized data records */ + this.recordValues = 0; + + /** ^^^This is wrong--variable sized padding */ + this.pad4 = 0; + + dis.RecordSet.prototype.initFromBinary = function(inputStream) + { + this.recordID = inputStream.readUInt(); + this.recordSetSerialNumber = inputStream.readUInt(); + this.recordLength = inputStream.readUShort(); + this.recordCount = inputStream.readUShort(); + this.recordValues = inputStream.readUShort(); + this.pad4 = inputStream.readUByte(); + }; + + dis.RecordSet.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.recordID); + outputStream.writeUInt(this.recordSetSerialNumber); + outputStream.writeUShort(this.recordLength); + outputStream.writeUShort(this.recordCount); + outputStream.writeUShort(this.recordValues); + outputStream.writeUByte(this.pad4); + }; +}; // end of class + + // node.js module support +exports.RecordSet = dis.RecordSet; + +// End of RecordSet class + +/** + * 5.2.56. Purpose for joinging two entities + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Relationship = function() +{ + /** Nature of join */ + this.nature = 0; + + /** position of join */ + this.position = 0; + + dis.Relationship.prototype.initFromBinary = function(inputStream) + { + this.nature = inputStream.readUShort(); + this.position = inputStream.readUShort(); + }; + + dis.Relationship.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.nature); + outputStream.writeUShort(this.position); + }; +}; // end of class + + // node.js module support +exports.Relationship = dis.Relationship; + +// End of Relationship class + +/** + * Section 5.3.6.2. Remove an entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 12; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.RemoveEntityPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityPdu = dis.RemoveEntityPdu; + +// End of RemoveEntityPdu class + +/** + * Section 5.3.12.2: Removal of an entity , reliable. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RemoveEntityReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 52; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.RemoveEntityReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.RemoveEntityReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.RemoveEntityReliablePdu = dis.RemoveEntityReliablePdu; + +// End of RemoveEntityReliablePdu class + +/** + * Section 5.2.5.5. Repair is complete. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairCompletePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 9; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Enumeration for type of repair */ + this.repair = 0; + + /** padding, number prevents conflict with superclass ivar name */ + this.padding2 = 0; + + dis.RepairCompletePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repair = inputStream.readUShort(); + this.padding2 = inputStream.readShort(); + }; + + dis.RepairCompletePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.repair); + outputStream.writeShort(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairCompletePdu = dis.RepairCompletePdu; + +// End of RepairCompletePdu class + +/** + * Section 5.2.5.6. Sent after repair complete PDU. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.RepairResponsePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 10; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.repairingEntityID = new dis.EntityID(); + + /** Result of repair operation */ + this.repairResult = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + dis.RepairResponsePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.repairingEntityID.initFromBinary(inputStream); + this.repairResult = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + }; + + dis.RepairResponsePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.repairingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.repairResult); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + }; +}; // end of class + + // node.js module support +exports.RepairResponsePdu = dis.RepairResponsePdu; + +// End of RepairResponsePdu class + +/** + * Section 5.2.5.4. Cancel of resupply by either the receiving or supplying entity. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyCancelPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 8; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + dis.ResupplyCancelPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + }; + + dis.ResupplyCancelPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.ResupplyCancelPdu = dis.ResupplyCancelPdu; + +// End of ResupplyCancelPdu class + +/** + * Section 5.3.5.2. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyOfferPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 6; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyOfferPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyOfferPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyOfferPdu = dis.ResupplyOfferPdu; + +// End of ResupplyOfferPdu class + +/** + * Section 5.3.5.3. Receipt of supplies is communiated. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ResupplyReceivedPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 7; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is receiving service */ + this.receivingEntityID = new dis.EntityID(); + + /** Entity that is supplying */ + this.supplyingEntityID = new dis.EntityID(); + + /** how many supplies are being offered */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.padding1 = 0; + + /** padding */ + this.padding2 = 0; + + this.supplies = new Array(); + + dis.ResupplyReceivedPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.receivingEntityID.initFromBinary(inputStream); + this.supplyingEntityID.initFromBinary(inputStream); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.padding2 = inputStream.readByte(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ResupplyReceivedPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.receivingEntityID.encodeToBinary(outputStream); + this.supplyingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.padding1); + outputStream.writeByte(this.padding2); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ResupplyReceivedPdu = dis.ResupplyReceivedPdu; + +// End of ResupplyReceivedPdu class + +/** + * Section 5.3.7.5. SEES PDU, supplemental emissions entity state information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SeesPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 30; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Originating entity ID */ + this.orginatingEntityID = new dis.EntityID(); + + /** IR Signature representation index */ + this.infraredSignatureRepresentationIndex = 0; + + /** acoustic Signature representation index */ + this.acousticSignatureRepresentationIndex = 0; + + /** radar cross section representation index */ + this.radarCrossSectionSignatureRepresentationIndex = 0; + + /** how many propulsion systems */ + this.numberOfPropulsionSystems = 0; + + /** how many vectoring nozzle systems */ + this.numberOfVectoringNozzleSystems = 0; + + /** variable length list of propulsion system data */ + this.propulsionSystemData = new Array(); + + /** variable length list of vectoring system data */ + this.vectoringSystemData = new Array(); + + dis.SeesPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.infraredSignatureRepresentationIndex = inputStream.readUShort(); + this.acousticSignatureRepresentationIndex = inputStream.readUShort(); + this.radarCrossSectionSignatureRepresentationIndex = inputStream.readUShort(); + this.numberOfPropulsionSystems = inputStream.readUShort(); + this.numberOfVectoringNozzleSystems = inputStream.readUShort(); + for(var idx = 0; idx < this.numberOfPropulsionSystems; idx++) + { + var anX = new dis.PropulsionSystemData(); + anX.initFromBinary(inputStream); + this.propulsionSystemData.push(anX); + } + + for(var idx = 0; idx < this.numberOfVectoringNozzleSystems; idx++) + { + var anX = new dis.VectoringNozzleSystemData(); + anX.initFromBinary(inputStream); + this.vectoringSystemData.push(anX); + } + + }; + + dis.SeesPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + outputStream.writeUShort(this.infraredSignatureRepresentationIndex); + outputStream.writeUShort(this.acousticSignatureRepresentationIndex); + outputStream.writeUShort(this.radarCrossSectionSignatureRepresentationIndex); + outputStream.writeUShort(this.numberOfPropulsionSystems); + outputStream.writeUShort(this.numberOfVectoringNozzleSystems); + for(var idx = 0; idx < this.propulsionSystemData.length; idx++) + { + propulsionSystemData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.vectoringSystemData.length; idx++) + { + vectoringSystemData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SeesPdu = dis.SeesPdu; + +// End of SeesPdu class + +/** + * Section 5.3.5.1. Information about a request for supplies. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ServiceRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 5; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 3; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is requesting service */ + this.requestingEntityID = new dis.EntityID(); + + /** Entity that is providing the service */ + this.servicingEntityID = new dis.EntityID(); + + /** type of service requested */ + this.serviceTypeRequested = 0; + + /** How many requested */ + this.numberOfSupplyTypes = 0; + + /** padding */ + this.serviceRequestPadding = 0; + + this.supplies = new Array(); + + dis.ServiceRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.requestingEntityID.initFromBinary(inputStream); + this.servicingEntityID.initFromBinary(inputStream); + this.serviceTypeRequested = inputStream.readUByte(); + this.numberOfSupplyTypes = inputStream.readUByte(); + this.serviceRequestPadding = inputStream.readShort(); + for(var idx = 0; idx < this.numberOfSupplyTypes; idx++) + { + var anX = new dis.SupplyQuantity(); + anX.initFromBinary(inputStream); + this.supplies.push(anX); + } + + }; + + dis.ServiceRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.requestingEntityID.encodeToBinary(outputStream); + this.servicingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.serviceTypeRequested); + outputStream.writeUByte(this.numberOfSupplyTypes); + outputStream.writeShort(this.serviceRequestPadding); + for(var idx = 0; idx < this.supplies.length; idx++) + { + supplies[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.ServiceRequestPdu = dis.ServiceRequestPdu; + +// End of ServiceRequestPdu class + +/** + * Section 5.3.6.9. Change state information with the data contained in this. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 19; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** ID of request */ + this.requestID = 0; + + /** padding */ + this.padding1 = 0; + + /** Number of fixed datum records */ + this.numberOfFixedDatumRecords = 0; + + /** Number of variable datum records */ + this.numberOfVariableDatumRecords = 0; + + /** variable length list of fixed datums */ + this.fixedDatums = new Array(); + + /** variable length list of variable length datums */ + this.variableDatums = new Array(); + + dis.SetDataPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.padding1 = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatums.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatums.push(anX); + } + + }; + + dis.SetDataPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.padding1); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatums.length; idx++) + { + fixedDatums[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatums.length; idx++) + { + variableDatums[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataPdu = dis.SetDataPdu; + +// End of SetDataPdu class + +/** + * Section 5.3.12.9: initializing or chaning internal state information, reliable. Needs manual intervention to fix padding on variable datums. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetDataReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 59; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + /** Fixed datum record count */ + this.numberOfFixedDatumRecords = 0; + + /** variable datum record count */ + this.numberOfVariableDatumRecords = 0; + + /** Fixed datum records */ + this.fixedDatumRecords = new Array(); + + /** Variable datum records */ + this.variableDatumRecords = new Array(); + + dis.SetDataReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + this.numberOfFixedDatumRecords = inputStream.readUInt(); + this.numberOfVariableDatumRecords = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfFixedDatumRecords; idx++) + { + var anX = new dis.FixedDatum(); + anX.initFromBinary(inputStream); + this.fixedDatumRecords.push(anX); + } + + for(var idx = 0; idx < this.numberOfVariableDatumRecords; idx++) + { + var anX = new dis.VariableDatum(); + anX.initFromBinary(inputStream); + this.variableDatumRecords.push(anX); + } + + }; + + dis.SetDataReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + outputStream.writeUInt(this.numberOfFixedDatumRecords); + outputStream.writeUInt(this.numberOfVariableDatumRecords); + for(var idx = 0; idx < this.fixedDatumRecords.length; idx++) + { + fixedDatumRecords[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.variableDatumRecords.length; idx++) + { + variableDatumRecords[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetDataReliablePdu = dis.SetDataReliablePdu; + +// End of SetDataReliablePdu class + +/** + * Section 5.3.12.14: Initializing or changing internal parameter info. Needs manual intervention to fix padding in recrod set PDUs. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SetRecordReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 64; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** request ID */ + this.requestID = 0; + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding. The spec is unclear and contradictory here. */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Number of record sets in list */ + this.numberOfRecordSets = 0; + + /** record sets */ + this.recordSets = new Array(); + + dis.SetRecordReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.numberOfRecordSets = inputStream.readUInt(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.SetRecordReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SetRecordReliablePdu = dis.SetRecordReliablePdu; + +// End of SetRecordReliablePdu class + +/** + * Shaft RPMs, used in underwater acoustic clacluations. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.ShaftRPMs = function() +{ + /** Current shaft RPMs */ + this.currentShaftRPMs = 0; + + /** ordered shaft rpms */ + this.orderedShaftRPMs = 0; + + /** rate of change of shaft RPMs */ + this.shaftRPMRateOfChange = 0; + + dis.ShaftRPMs.prototype.initFromBinary = function(inputStream) + { + this.currentShaftRPMs = inputStream.readShort(); + this.orderedShaftRPMs = inputStream.readShort(); + this.shaftRPMRateOfChange = inputStream.readFloat32(); + }; + + dis.ShaftRPMs.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeShort(this.currentShaftRPMs); + outputStream.writeShort(this.orderedShaftRPMs); + outputStream.writeFloat32(this.shaftRPMRateOfChange); + }; +}; // end of class + + // node.js module support +exports.ShaftRPMs = dis.ShaftRPMs; + +// End of ShaftRPMs class + +/** + * Section 5.3.8.2. Detailed information about a radio transmitter. This PDU requires manually written code to complete. The encodingScheme field can be used in multiple ways, which requires hand-written code to finish. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SignalPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 26; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** encoding scheme used, and enumeration */ + this.encodingScheme = 0; + + /** tdl type */ + this.tdlType = 0; + + /** sample rate */ + this.sampleRate = 0; + + /** length of data, in bits */ + this.dataLength = 0; + + /** number of samples. If the PDU contains encoded audio, this should be zero. */ + this.samples = 0; + + /** list of eight bit values. Must be padded to fall on a 32 bit boundary. */ + this.data = new Array(); + + dis.SignalPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.encodingScheme = inputStream.readUShort(); + this.tdlType = inputStream.readUShort(); + this.sampleRate = inputStream.readUInt(); + this.dataLength = inputStream.readUShort(); + this.samples = inputStream.readUShort(); + for(var idx = 0; idx < this.dataLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.data.push(anX); + } + + }; + + dis.SignalPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + outputStream.writeUShort(this.encodingScheme); + outputStream.writeUShort(this.tdlType); + outputStream.writeUInt(this.sampleRate); + outputStream.writeUShort(this.dataLength); + outputStream.writeUShort(this.samples); + for(var idx = 0; idx < this.data.length; idx++) + { + data[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.SignalPdu = dis.SignalPdu; + +// End of SignalPdu class + +/** + * Section 5.2.14.1. A Simulation Address record shall consist of the Site Identification number and the Application Identification number. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationAddress = function() +{ + /** The site ID */ + this.site = 0; + + /** The application ID */ + this.application = 0; + + dis.SimulationAddress.prototype.initFromBinary = function(inputStream) + { + this.site = inputStream.readUShort(); + this.application = inputStream.readUShort(); + }; + + dis.SimulationAddress.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.site); + outputStream.writeUShort(this.application); + }; +}; // end of class + + // node.js module support +exports.SimulationAddress = dis.SimulationAddress; + +// End of SimulationAddress class + +/** + * Section 5.3.6. Abstract superclass for PDUs relating to the simulation itself. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementFamilyPdu = dis.SimulationManagementFamilyPdu; + +// End of SimulationManagementFamilyPdu class + +/** + * Section 5.3.12: Abstract superclass for reliable simulation management PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SimulationManagementWithReliabilityFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + }; + + dis.SimulationManagementWithReliabilityFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.SimulationManagementWithReliabilityFamilyPdu = dis.SimulationManagementWithReliabilityFamilyPdu; + +// End of SimulationManagementWithReliabilityFamilyPdu class + +/** + * 48 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SixByteChunk = function() +{ + /** six bytes of arbitrary data */ + this.otherParameters = new Array(0, 0, 0, 0, 0, 0); + + dis.SixByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 6; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.SixByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 6; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.SixByteChunk = dis.SixByteChunk; + +// End of SixByteChunk class + +/** + * Section 5.2.4.3. Used when the antenna pattern type in the transmitter pdu is of value 2. Specified the direction and radiation pattern from a radio transmitter's antenna. NOTE: this class must be hand-coded to clean up some implementation details. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SphericalHarmonicAntennaPattern = function() +{ + this.harmonicOrder = 0; + + dis.SphericalHarmonicAntennaPattern.prototype.initFromBinary = function(inputStream) + { + this.harmonicOrder = inputStream.readByte(); + }; + + dis.SphericalHarmonicAntennaPattern.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeByte(this.harmonicOrder); + }; +}; // end of class + + // node.js module support +exports.SphericalHarmonicAntennaPattern = dis.SphericalHarmonicAntennaPattern; + +// End of SphericalHarmonicAntennaPattern class + +/** + * Section 5.2.6.3. Start or resume an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 13; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall start or resume */ + this.realWorldTime = new dis.ClockTime(); + + /** Simulation clock time at which the simulation shall start or resume */ + this.simulationTime = new dis.ClockTime(); + + /** Identifier for the request */ + this.requestID = 0; + + dis.StartResumePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumePdu = dis.StartResumePdu; + +// End of StartResumePdu class + +/** + * Section 5.3.12.3: Start resume simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StartResumeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 53; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** time in simulation for the simulation to resume */ + this.simulationTime = new dis.ClockTime(); + + /** level of reliability service used for this transaction */ + this.requiredReliabilityService = 0; + + /** padding */ + this.pad1 = 0; + + /** padding */ + this.pad2 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StartResumeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.simulationTime.initFromBinary(inputStream); + this.requiredReliabilityService = inputStream.readUByte(); + this.pad1 = inputStream.readUShort(); + this.pad2 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StartResumeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + this.simulationTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUShort(this.pad1); + outputStream.writeUByte(this.pad2); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StartResumeReliablePdu = dis.StartResumeReliablePdu; + +// End of StartResumeReliablePdu class + +/** + * Section 5.2.3.4. Stop or freeze an exercise. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 14; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 5; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Entity that is sending message */ + this.originatingEntityID = new dis.EntityID(); + + /** Entity that is intended to receive message */ + this.receivingEntityID = new dis.EntityID(); + + /** UTC time at which the simulation shall stop or freeze */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason the simulation was stopped or frozen */ + this.reason = 0; + + /** Internal behavior of the simulation and its appearance while frozento the other participants */ + this.frozenBehavior = 0; + + /** padding */ + this.padding1 = 0; + + /** Request ID that is unique */ + this.requestID = 0; + + dis.StopFreezePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.padding1 = inputStream.readShort(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeShort(this.padding1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezePdu = dis.StopFreezePdu; + +// End of StopFreezePdu class + +/** + * Section 5.3.12.4: Stop freeze simulation, relaible. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.StopFreezeReliablePdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 54; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 10; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** Object originatig the request */ + this.originatingEntityID = new dis.EntityID(); + + /** Object with which this point object is associated */ + this.receivingEntityID = new dis.EntityID(); + + /** time in real world for this operation to happen */ + this.realWorldTime = new dis.ClockTime(); + + /** Reason for stopping/freezing simulation */ + this.reason = 0; + + /** internal behvior of the simulation while frozen */ + this.frozenBehavior = 0; + + /** reliablity level */ + this.requiredReliablityService = 0; + + /** padding */ + this.pad1 = 0; + + /** Request ID */ + this.requestID = 0; + + dis.StopFreezeReliablePdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.originatingEntityID.initFromBinary(inputStream); + this.receivingEntityID.initFromBinary(inputStream); + this.realWorldTime.initFromBinary(inputStream); + this.reason = inputStream.readUByte(); + this.frozenBehavior = inputStream.readUByte(); + this.requiredReliablityService = inputStream.readUByte(); + this.pad1 = inputStream.readUByte(); + this.requestID = inputStream.readUInt(); + }; + + dis.StopFreezeReliablePdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.originatingEntityID.encodeToBinary(outputStream); + this.receivingEntityID.encodeToBinary(outputStream); + this.realWorldTime.encodeToBinary(outputStream); + outputStream.writeUByte(this.reason); + outputStream.writeUByte(this.frozenBehavior); + outputStream.writeUByte(this.requiredReliablityService); + outputStream.writeUByte(this.pad1); + outputStream.writeUInt(this.requestID); + }; +}; // end of class + + // node.js module support +exports.StopFreezeReliablePdu = dis.StopFreezeReliablePdu; + +// End of StopFreezeReliablePdu class + +/** + * Section 5.2.30. A supply, and the amount of that supply. Similar to an entity kind but with the addition of a quantity. + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SupplyQuantity = function() +{ + /** Type of supply */ + this.supplyType = new dis.EntityType(); + + /** quantity to be supplied */ + this.quantity = 0; + + dis.SupplyQuantity.prototype.initFromBinary = function(inputStream) + { + this.supplyType.initFromBinary(inputStream); + this.quantity = inputStream.readUByte(); + }; + + dis.SupplyQuantity.prototype.encodeToBinary = function(outputStream) + { + this.supplyType.encodeToBinary(outputStream); + outputStream.writeUByte(this.quantity); + }; +}; // end of class + + // node.js module support +exports.SupplyQuantity = dis.SupplyQuantity; + +// End of SupplyQuantity class + +/** + * Section 5.3.11: Abstract superclass for synthetic environment PDUs + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SyntheticEnvironmentFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 9; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + dis.SyntheticEnvironmentFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + }; + + dis.SyntheticEnvironmentFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + }; +}; // end of class + + // node.js module support +exports.SyntheticEnvironmentFamilyPdu = dis.SyntheticEnvironmentFamilyPdu; + +// End of SyntheticEnvironmentFamilyPdu class + +/** + * 5.2.58. Used in IFF ATC PDU + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.SystemID = function() +{ + /** System Type */ + this.systemType = 0; + + /** System name, an enumeration */ + this.systemName = 0; + + /** System mode */ + this.systemMode = 0; + + /** Change Options */ + this.changeOptions = 0; + + dis.SystemID.prototype.initFromBinary = function(inputStream) + { + this.systemType = inputStream.readUShort(); + this.systemName = inputStream.readUShort(); + this.systemMode = inputStream.readUByte(); + this.changeOptions = inputStream.readUByte(); + }; + + dis.SystemID.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUShort(this.systemType); + outputStream.writeUShort(this.systemName); + outputStream.writeUByte(this.systemMode); + outputStream.writeUByte(this.changeOptions); + }; +}; // end of class + + // node.js module support +exports.SystemID = dis.SystemID; + +// End of SystemID class + +/** + * One track/jam target + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TrackJamTarget = function() +{ + /** track/jam target */ + this.trackJam = new dis.EntityID(); + + /** Emitter ID */ + this.emitterID = 0; + + /** beam ID */ + this.beamID = 0; + + dis.TrackJamTarget.prototype.initFromBinary = function(inputStream) + { + this.trackJam.initFromBinary(inputStream); + this.emitterID = inputStream.readUByte(); + this.beamID = inputStream.readUByte(); + }; + + dis.TrackJamTarget.prototype.encodeToBinary = function(outputStream) + { + this.trackJam.encodeToBinary(outputStream); + outputStream.writeUByte(this.emitterID); + outputStream.writeUByte(this.beamID); + }; +}; // end of class + + // node.js module support +exports.TrackJamTarget = dis.TrackJamTarget; + +// End of TrackJamTarget class + +/** + * Section 5.3.9.3 Information initiating the dyanic allocation and control of simulation entities between two simulation applications. Requires manual cleanup. The padding between record sets is variable. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransferControlRequestPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 35; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 7; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of entity originating request */ + this.orginatingEntityID = new dis.EntityID(); + + /** ID of entity receiving request */ + this.recevingEntityID = new dis.EntityID(); + + /** ID ofrequest */ + this.requestID = 0; + + /** required level of reliabliity service. */ + this.requiredReliabilityService = 0; + + /** type of transfer desired */ + this.tranferType = 0; + + /** The entity for which control is being requested to transfer */ + this.transferEntityID = new dis.EntityID(); + + /** number of record sets to transfer */ + this.numberOfRecordSets = 0; + + /** ^^^This is wrong--the RecordSet class needs more work */ + this.recordSets = new Array(); + + dis.TransferControlRequestPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.orginatingEntityID.initFromBinary(inputStream); + this.recevingEntityID.initFromBinary(inputStream); + this.requestID = inputStream.readUInt(); + this.requiredReliabilityService = inputStream.readUByte(); + this.tranferType = inputStream.readUByte(); + this.transferEntityID.initFromBinary(inputStream); + this.numberOfRecordSets = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfRecordSets; idx++) + { + var anX = new dis.RecordSet(); + anX.initFromBinary(inputStream); + this.recordSets.push(anX); + } + + }; + + dis.TransferControlRequestPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.orginatingEntityID.encodeToBinary(outputStream); + this.recevingEntityID.encodeToBinary(outputStream); + outputStream.writeUInt(this.requestID); + outputStream.writeUByte(this.requiredReliabilityService); + outputStream.writeUByte(this.tranferType); + this.transferEntityID.encodeToBinary(outputStream); + outputStream.writeUByte(this.numberOfRecordSets); + for(var idx = 0; idx < this.recordSets.length; idx++) + { + recordSets[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransferControlRequestPdu = dis.TransferControlRequestPdu; + +// End of TransferControlRequestPdu class + +/** + * Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete, since the modulation parameters are of variable length. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TransmitterPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 25; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 4; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the communication, ie contains the radio */ + this.entityId = new dis.EntityID(); + + /** particular radio within an entity */ + this.radioId = 0; + + /** linear accelleration of entity */ + this.radioEntityType = new dis.RadioEntityType(); + + /** transmit state */ + this.transmitState = 0; + + /** input source */ + this.inputSource = 0; + + /** padding */ + this.padding1 = 0; + + /** Location of antenna */ + this.antennaLocation = new dis.Vector3Double(); + + /** relative location of antenna, in entity coordinates */ + this.relativeAntennaLocation = new dis.Vector3Float(); + + /** antenna pattern type */ + this.antennaPatternType = 0; + + /** atenna pattern length */ + this.antennaPatternCount = 0; + + /** frequency */ + this.frequency = 0; + + /** transmit frequency Bandwidth */ + this.transmitFrequencyBandwidth = 0; + + /** transmission power */ + this.power = 0; + + /** modulation */ + this.modulationType = new dis.ModulationType(); + + /** crypto system enumeration */ + this.cryptoSystem = 0; + + /** crypto system key identifer */ + this.cryptoKeyId = 0; + + /** how many modulation parameters we have */ + this.modulationParameterCount = 0; + + /** padding2 */ + this.padding2 = 0; + + /** padding3 */ + this.padding3 = 0; + + /** variable length list of modulation parameters */ + this.modulationParametersList = new Array(); + + /** variable length list of antenna pattern records */ + this.antennaPatternList = new Array(); + + dis.TransmitterPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.entityId.initFromBinary(inputStream); + this.radioId = inputStream.readUShort(); + this.radioEntityType.initFromBinary(inputStream); + this.transmitState = inputStream.readUByte(); + this.inputSource = inputStream.readUByte(); + this.padding1 = inputStream.readUShort(); + this.antennaLocation.initFromBinary(inputStream); + this.relativeAntennaLocation.initFromBinary(inputStream); + this.antennaPatternType = inputStream.readUShort(); + this.antennaPatternCount = inputStream.readUShort(); + this.frequency = inputStream.readLong(); + this.transmitFrequencyBandwidth = inputStream.readFloat32(); + this.power = inputStream.readFloat32(); + this.modulationType.initFromBinary(inputStream); + this.cryptoSystem = inputStream.readUShort(); + this.cryptoKeyId = inputStream.readUShort(); + this.modulationParameterCount = inputStream.readUByte(); + this.padding2 = inputStream.readUShort(); + this.padding3 = inputStream.readUByte(); + for(var idx = 0; idx < this.modulationParameterCount; idx++) + { + var anX = new dis.ModulationType(); + anX.initFromBinary(inputStream); + this.modulationParametersList.push(anX); + } + + for(var idx = 0; idx < this.antennaPatternCount; idx++) + { + var anX = new dis.BeamAntennaPattern(); + anX.initFromBinary(inputStream); + this.antennaPatternList.push(anX); + } + + }; + + dis.TransmitterPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.entityId.encodeToBinary(outputStream); + outputStream.writeUShort(this.radioId); + this.radioEntityType.encodeToBinary(outputStream); + outputStream.writeUByte(this.transmitState); + outputStream.writeUByte(this.inputSource); + outputStream.writeUShort(this.padding1); + this.antennaLocation.encodeToBinary(outputStream); + this.relativeAntennaLocation.encodeToBinary(outputStream); + outputStream.writeUShort(this.antennaPatternType); + outputStream.writeUShort(this.antennaPatternCount); + outputStream.writeLong(this.frequency); + outputStream.writeFloat32(this.transmitFrequencyBandwidth); + outputStream.writeFloat32(this.power); + this.modulationType.encodeToBinary(outputStream); + outputStream.writeUShort(this.cryptoSystem); + outputStream.writeUShort(this.cryptoKeyId); + outputStream.writeUByte(this.modulationParameterCount); + outputStream.writeUShort(this.padding2); + outputStream.writeUByte(this.padding3); + for(var idx = 0; idx < this.modulationParametersList.length; idx++) + { + modulationParametersList[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.antennaPatternList.length; idx++) + { + antennaPatternList[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.TransmitterPdu = dis.TransmitterPdu; + +// End of TransmitterPdu class + +/** + * 16 bit piece of data + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.TwoByteChunk = function() +{ + /** two bytes of arbitrary data */ + this.otherParameters = new Array(0, 0); + + dis.TwoByteChunk.prototype.initFromBinary = function(inputStream) + { + for(var idx = 0; idx < 2; idx++) + { + this.otherParameters[ idx ] = inputStream.readByte(); + } + }; + + dis.TwoByteChunk.prototype.encodeToBinary = function(outputStream) + { + for(var idx = 0; idx < 2; idx++) + { + outputStream.writeByte(this.otherParameters[ idx ] ); + } + }; +}; // end of class + + // node.js module support +exports.TwoByteChunk = dis.TwoByteChunk; + +// End of TwoByteChunk class + +/** + * Section 5.3.7.3. Information about underwater acoustic emmissions. This requires manual cleanup. The beam data records should ALL be a the finish, rather than attached to each emitter system. UNFINISHED + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UaPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 29; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 6; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that is the source of the emission */ + this.emittingEntityID = new dis.EntityID(); + + /** ID of event */ + this.eventID = new dis.EventID(); + + /** This field shall be used to indicate whether the data in the UA PDU represent a state update or data that have changed since issuance of the last UA PDU */ + this.stateChangeIndicator = 0; + + /** padding */ + this.pad = 0; + + /** This field indicates which database record (or file) shall be used in the definition of passive signature (unintentional) emissions of the entity. The indicated database record (or file) shall define all noise generated as a function of propulsion plant configurations and associated auxiliaries. */ + this.passiveParameterIndex = 0; + + /** This field shall specify the entity propulsion plant configuration. This field is used to determine the passive signature characteristics of an entity. */ + this.propulsionPlantConfiguration = 0; + + /** This field shall represent the number of shafts on a platform */ + this.numberOfShafts = 0; + + /** This field shall indicate the number of APAs described in the current UA PDU */ + this.numberOfAPAs = 0; + + /** This field shall specify the number of UA emitter systems being described in the current UA PDU */ + this.numberOfUAEmitterSystems = 0; + + /** shaft RPM values */ + this.shaftRPMs = new Array(); + + /** apaData */ + this.apaData = new Array(); + + this.emitterSystems = new Array(); + + dis.UaPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.emittingEntityID.initFromBinary(inputStream); + this.eventID.initFromBinary(inputStream); + this.stateChangeIndicator = inputStream.readByte(); + this.pad = inputStream.readByte(); + this.passiveParameterIndex = inputStream.readUShort(); + this.propulsionPlantConfiguration = inputStream.readUByte(); + this.numberOfShafts = inputStream.readUByte(); + this.numberOfAPAs = inputStream.readUByte(); + this.numberOfUAEmitterSystems = inputStream.readUByte(); + for(var idx = 0; idx < this.numberOfShafts; idx++) + { + var anX = new dis.ShaftRPMs(); + anX.initFromBinary(inputStream); + this.shaftRPMs.push(anX); + } + + for(var idx = 0; idx < this.numberOfAPAs; idx++) + { + var anX = new dis.ApaData(); + anX.initFromBinary(inputStream); + this.apaData.push(anX); + } + + for(var idx = 0; idx < this.numberOfUAEmitterSystems; idx++) + { + var anX = new dis.AcousticEmitterSystemData(); + anX.initFromBinary(inputStream); + this.emitterSystems.push(anX); + } + + }; + + dis.UaPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.emittingEntityID.encodeToBinary(outputStream); + this.eventID.encodeToBinary(outputStream); + outputStream.writeByte(this.stateChangeIndicator); + outputStream.writeByte(this.pad); + outputStream.writeUShort(this.passiveParameterIndex); + outputStream.writeUByte(this.propulsionPlantConfiguration); + outputStream.writeUByte(this.numberOfShafts); + outputStream.writeUByte(this.numberOfAPAs); + outputStream.writeUByte(this.numberOfUAEmitterSystems); + for(var idx = 0; idx < this.shaftRPMs.length; idx++) + { + shaftRPMs[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.apaData.length; idx++) + { + apaData[idx].encodeToBinary(outputStream); + } + + for(var idx = 0; idx < this.emitterSystems.length; idx++) + { + emitterSystems[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.UaPdu = dis.UaPdu; + +// End of UaPdu class + +/** + * Wrapper for an unsigned 32 bit integer + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.UnsignedIntegerWrapper = function() +{ + /** name can't be too accurate or the generated source code will have reserved word problems */ + this.wrapper = 0; + + dis.UnsignedIntegerWrapper.prototype.initFromBinary = function(inputStream) + { + this.wrapper = inputStream.readUInt(); + }; + + dis.UnsignedIntegerWrapper.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.wrapper); + }; +}; // end of class + + // node.js module support +exports.UnsignedIntegerWrapper = dis.UnsignedIntegerWrapper; + +// End of UnsignedIntegerWrapper class + +/** + * Section 5.2.32. Variable Datum Record + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VariableDatum = function() +{ + /** ID of the variable datum */ + this.variableDatumID = 0; + + /** length of the variable datums, in bits. Note that this is not programmatically tied to the size of the variableData. The variable data field may be 64 bits long but only 16 bits of it could actually be used. */ + this.variableDatumLength = 0; + + /** data can be any length, but must increase in 8 byte quanta. This requires some postprocessing patches. Note that setting the data allocates a new internal array to account for the possibly increased size. The default initial size is 64 bits. */ + this.variableData = new Array(); + + dis.VariableDatum.prototype.initFromBinary = function(inputStream) + { + this.variableDatumID = inputStream.readUInt(); + this.variableDatumLength = inputStream.readUInt(); + for(var idx = 0; idx < this.variableDatumLength; idx++) + { + var anX = new dis.OneByteChunk(); + anX.initFromBinary(inputStream); + this.variableData.push(anX); + } + + }; + + dis.VariableDatum.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUInt(this.variableDatumID); + outputStream.writeUInt(this.variableDatumLength); + for(var idx = 0; idx < this.variableData.length; idx++) + { + variableData[idx].encodeToBinary(outputStream); + } + + }; +}; // end of class + + // node.js module support +exports.VariableDatum = dis.VariableDatum; + +// End of VariableDatum class + +/** + * Section 5.3.34. Three double precision floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Double = function() +{ + /** X value */ + this.x = 0; + + /** Y value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Double.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat64(); + this.y = inputStream.readFloat64(); + this.z = inputStream.readFloat64(); + }; + + dis.Vector3Double.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat64(this.x); + outputStream.writeFloat64(this.y); + outputStream.writeFloat64(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Double = dis.Vector3Double; + +// End of Vector3Double class + +/** + * Section 5.2.33. Three floating point values, x, y, and z + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.Vector3Float = function() +{ + /** X value */ + this.x = 0; + + /** y Value */ + this.y = 0; + + /** Z value */ + this.z = 0; + + dis.Vector3Float.prototype.initFromBinary = function(inputStream) + { + this.x = inputStream.readFloat32(); + this.y = inputStream.readFloat32(); + this.z = inputStream.readFloat32(); + }; + + dis.Vector3Float.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.x); + outputStream.writeFloat32(this.y); + outputStream.writeFloat32(this.z); + }; +}; // end of class + + // node.js module support +exports.Vector3Float = dis.Vector3Float; + +// End of Vector3Float class + +/** + * Data about a vectoring nozzle system + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.VectoringNozzleSystemData = function() +{ + /** horizontal deflection angle */ + this.horizontalDeflectionAngle = 0; + + /** vertical deflection angle */ + this.verticalDeflectionAngle = 0; + + dis.VectoringNozzleSystemData.prototype.initFromBinary = function(inputStream) + { + this.horizontalDeflectionAngle = inputStream.readFloat32(); + this.verticalDeflectionAngle = inputStream.readFloat32(); + }; + + dis.VectoringNozzleSystemData.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeFloat32(this.horizontalDeflectionAngle); + outputStream.writeFloat32(this.verticalDeflectionAngle); + }; +}; // end of class + + // node.js module support +exports.VectoringNozzleSystemData = dis.VectoringNozzleSystemData; + +// End of VectoringNozzleSystemData class + +/** + * Section 5.3.4. abstract superclass for fire and detonation pdus that have shared information. COMPLETE + * + * Copyright (c) 2008-2015, MOVES Institute, Naval Postgraduate School. All rights reserved. + * This work is licensed under the BSD open source license, available at https://www.movesinstitute.org/licenses/bsd.html + * + * @author DMcG + */ +// On the client side, support for a namespace. +if (typeof dis === "undefined") + dis = {}; + + +// Support for node.js style modules. Ignored if used in a client context. +// See http://howtonode.org/creating-custom-modules +if (typeof exports === "undefined") + exports = {}; + + +dis.WarfareFamilyPdu = function() +{ + /** The version of the protocol. 5=DIS-1995, 6=DIS-1998. */ + this.protocolVersion = 6; + + /** Exercise ID */ + this.exerciseID = 0; + + /** Type of pdu, unique for each PDU class */ + this.pduType = 0; + + /** value that refers to the protocol family, eg SimulationManagement, et */ + this.protocolFamily = 2; + + /** Timestamp value */ + this.timestamp = 0; + + /** Length, in bytes, of the PDU. Changed name from length to avoid use of Hibernate QL reserved word */ + this.pduLength = 0; + + /** zero-filled array of padding */ + this.padding = 0; + + /** ID of the entity that shot */ + this.firingEntityID = new dis.EntityID(); + + /** ID of the entity that is being shot at */ + this.targetEntityID = new dis.EntityID(); + + dis.WarfareFamilyPdu.prototype.initFromBinary = function(inputStream) + { + this.protocolVersion = inputStream.readUByte(); + this.exerciseID = inputStream.readUByte(); + this.pduType = inputStream.readUByte(); + this.protocolFamily = inputStream.readUByte(); + this.timestamp = inputStream.readUInt(); + this.pduLength = inputStream.readUShort(); + this.padding = inputStream.readShort(); + this.firingEntityID.initFromBinary(inputStream); + this.targetEntityID.initFromBinary(inputStream); + }; + + dis.WarfareFamilyPdu.prototype.encodeToBinary = function(outputStream) + { + outputStream.writeUByte(this.protocolVersion); + outputStream.writeUByte(this.exerciseID); + outputStream.writeUByte(this.pduType); + outputStream.writeUByte(this.protocolFamily); + outputStream.writeUInt(this.timestamp); + outputStream.writeUShort(this.pduLength); + outputStream.writeShort(this.padding); + this.firingEntityID.encodeToBinary(outputStream); + this.targetEntityID.encodeToBinary(outputStream); + }; +}; // end of class + + // node.js module support +exports.WarfareFamilyPdu = dis.WarfareFamilyPdu; + +// End of WarfareFamilyPdu class + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/main.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/main.js new file mode 100644 index 0000000000000000000000000000000000000000..bc28a3a516362a300ec801a57d1681dee862884d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/main.js @@ -0,0 +1,251 @@ + /** This works if you're running client and server on one host. To + * have it work with a remote server, replace localhost with the IP + * or name of the server. + */ + + + var WEBSOCKET_URL="ws://track.movesinstitute.org:80"; + var websocket; + var timerID = 0; + /** A likely map location */ + var montereyLocation = {'latitude':36.595, 'longitude':-121.877}; + var allDisEntities = new Object(); + var pduFactory = new dis.PduFactory(); + var espdu = new dis.EntityStatePdu(); + + var rifleMunition = new dis.EntityType(); + var damageHits = 0; + + + espdu.entityID.entity = Math.round(Math.random() * 64000); + + /** + * Called when the user clicks the "submit" button. Starts a task + * to retrieve the field values, and periodically send ESPDUs based + * on this. + * + * @param {type} form + * @returns {undefined} + */ + function constructiveSend(form) + { + // On a second button press, kill the old send timer and + // start a new one farther down, so we don't have two + // timers sending + if(timerID != 0) + { + console.log("timerID:", timerID) + clearInterval(timerID); + console.log("Killed old periodic send task") + } + + // Fill out entity type info + espdu.entityType.entityKind = parseInt(document.getElementById("entitykind").value); + espdu.entityType.domain = parseInt(document.getElementById("domain").value); + espdu.entityType.country = parseInt(document.getElementById("country").value); + espdu.entityType.category = parseInt(document.getElementById("category").value); + espdu.entityType.subcategory = parseInt(document.getElementById("subcategory").value); + espdu.entityType.specific = parseInt(document.getElementById("specific").value); + espdu.entityType.extra = parseInt(document.getElementById("extra").value); + + // Fill out entity ID + espdu.entityID.site = parseInt(document.getElementById("site").value); + espdu.entityID.application = parseInt(document.getElementById("application").value); + espdu.entityID.entity = Math.round(Math.random() * 65000); + + // Marking + var convert = new dis.StringConversion(); + + espdu.marking.setMarking(document.getElementById("marking").value); + + // Position + var lat = parseFloat(document.getElementById("latitude").value); + var lon = parseFloat(document.getElementById("longitude").value); + var alt = parseFloat(document.getElementById("altitude").value); + + // Convert lat/lon/alt to DIS coordinates + var conversion = new dis.CoordinateConversion(); + latLonAlt = {}; + latLonAlt.lat = lat; + latLonAlt.lon = lon; + latLonAlt.alt = alt; + console.log("Geodetic location:", latLonAlt); + + var disCoordinates = conversion.getXYZfromLatLonAltDegrees(latLonAlt); + espdu.entityLocation.x = disCoordinates.x; + espdu.entityLocation.y = disCoordinates.y; + espdu.entityLocation.z = disCoordinates.z; + console.log("Location:", disCoordinates); + + // How often to send + var frequency = parseInt(document.getElementById("sendfrequency").value); + + // start a repeating task to send it + timerID = setInterval(sendPdu, frequency); + } + + /** + * Called by the timer task. Marshal and send a PDU + * + * @returns {undefined} + */ + function sendPdu() + { + var dataBuffer = new ArrayBuffer(1000); // typically 144 bytes, make it bigger for safety + var outputStream = new dis.OutputStream(dataBuffer); + espdu.encodeToBinary(outputStream); + + var trimmedData = outputStream.toByteArray(); + websocket.send(trimmedData); + console.log("Sent pdu ", espdu); + + } + + /** + * Initialize websocket + * + * @returns {undefined} + */ + function initialize() + { + + websocket = new WebSocket(WEBSOCKET_URL); + + // Set the format we want to use to receive binary messages + websocket.binaryType = 'arraybuffer'; + + // Attach functions to the the web socket for various events + websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; + websocket.onclose = function(evt){console.log("websocket close", evt);}; + websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + // We don't really need to receive anything, just blindly send + websocket.onmessage = function(evt) + { + var aPdu = pduFactory.createPdu(evt.data); + //console.log("PDU:", aPdu); + switch(aPdu.pduType) + { + case 1: + entityStatePduHandler(aPdu); + break; + + case 2: + console.log("Fire PDU:", aPdu); + firePduHandler(aPdu); + break; + + case 3: + console.log("Detonation PDU"); + detonationPduHandler(aPdu); + break; + + default: + break; + } + + } + + } + + /** + * Call this function to process an entity state pdu + * + * @param {EntityStatePdu} espdu + * @returns {void} + */ + function entityStatePduHandler(espdu) + { + if(espdu.pduType != 1) + { + console.log("Sent a non-espdu PDU to entityStatePduHandler"); + return; + } + + // Process an entity state PDU here + } + + + /** + * Call this function to process a FirePdu + * + * @param {FirePdu} firePdu + * @returns {void} + */ + function firePduHandler(firePdu) + { + if(firePdu.pduType != 2) + { + console.log("You sent a PDU that is not a fire PDU to firePduHandler"); + return; + } + + // Process PDU here + } + + /** + * Call this function to process a detonation pdu + * + * @param {DetonationPdu} detonationPdu + * @returns {void} + */ + function detonationPduHandler(detonationPdu) + { + if(detonationPdu.pduType != 3) + { + console.log("You sent a PDU that is not a detonation pdu to detonationPduHandler"); + return; + } + + // Handle the detonation PDU here + + } + + /** + * Write code to assess damage to our entity here. Assume + * that we are killed by two or more 5.56 rifle rounds that + * hit us. We receive the detonation PDU, which contains the + * target ID and the munition. if 1) we're the target, and + * 2) the munition is a rifle round, and (3) the impact + * is in the general area, assume we've been shot. You can + * make use of the entityIDsEqual() and munitionsEqual() + * functions. + * + * @param {type} detonationPdu + * @returns {undefined} + */ + function assessDamageToOurEntities(detonationPdu) + { + console.log("Assessing damage for detonation:", detonationPdu); + } + + function entityIDsEqual(eid1, eid2) + { + if(eid1.site === eid2.site && + eid1.application === eid2.application && + eid1.entity === eid2.entity) + { + return true; + } + + return false; + } + + + function munitionsEqual(firstMunition, secondMunition) + { + if(firstMunition.domain === secondMunition.domain && + firstMunition.entityKind === secondMunition.entityKind && + firstMunition.country === secondMunition.country && + firstMunition.category === secondMunition.category && + firstMunition.subcategory === secondMunition.subcategory && + firstMunition.specific === secondMunition.specific && + firstMunition.extra === secondMunition.extra) + { + return true; + } + + return false; + } + + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/multicastListen.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/multicastListen.js new file mode 100644 index 0000000000000000000000000000000000000000..eedabb26d24dcb54fd411f5501ab142d68f45f73 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/multicastListen.js @@ -0,0 +1,30 @@ +//listen to muticast +var PORT = 1415; +var HOST = 'localhost'; + +var dgram = require('dgram'); +var server = dgram.createSocket('udp4'); +const WebSocket = require('ws'); + +const websocket = new WebSocket('ws://track.movesinstitute.org:80'); + +websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; +websocket.onclose = function(evt){console.log("websocket close", evt);}; +websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + + + +server.on('listening', function () { + var address = server.address(); + console.log('UDP Server listening on ' + address.address + ":" + address.port); +}); + +server.on('message', function (message, remote) { + console.log(remote.address + ':' + remote.port +' - ' + message); + websocket.send(message); + +}); + +server.bind(PORT, HOST); + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..6cf4a7ad0b7c6317691d092c261498868ab22b53 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/.travis.yml @@ -0,0 +1,7 @@ +language: node_js +node_js: + - "6" + - "node" +script: npm run travis +cache: + yarn: true diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..9c91fb26803ab91013ece7c825691b3c29d3abb6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/LICENSE @@ -0,0 +1,8 @@ +The MIT License (MIT) +Copyright (c) 2017 Samuel Reed <samuel.trace.reed@gmail.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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/coverage.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/coverage.json new file mode 100644 index 0000000000000000000000000000000000000000..5b4a358483e011ff99119eccd56cf4fd48f2e56a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/coverage.json @@ -0,0 +1 @@ +{"/Users/samuelreed/git/forks/async-throttle/index.js":{"path":"/Users/samuelreed/git/forks/async-throttle/index.js","s":{"1":1,"2":7,"3":1,"4":6,"5":6,"6":6,"7":6,"8":6,"9":6,"10":1,"11":1,"12":3,"13":13,"14":13,"15":13,"16":1,"17":19,"18":1,"19":45,"20":6,"21":39,"22":13,"23":13,"24":13,"25":13,"26":39,"27":18,"28":6,"29":6,"30":1,"31":6,"32":6,"33":6,"34":1,"35":13,"36":13,"37":1},"b":{"1":[1,6],"2":[6,5],"3":[6,5],"4":[6,39],"5":[13,26],"6":[18,21],"7":[6,0]},"f":{"1":7,"2":3,"3":13,"4":19,"5":45,"6":6,"7":13},"fnMap":{"1":{"name":"Queue","line":3,"loc":{"start":{"line":3,"column":0},"end":{"line":3,"column":24}}},"2":{"name":"(anonymous_2)","line":22,"loc":{"start":{"line":22,"column":24},"end":{"line":22,"column":41}}},"3":{"name":"(anonymous_3)","line":23,"loc":{"start":{"line":23,"column":28},"end":{"line":23,"column":39}}},"4":{"name":"(anonymous_4)","line":31,"loc":{"start":{"line":31,"column":7},"end":{"line":31,"column":18}}},"5":{"name":"(anonymous_5)","line":36,"loc":{"start":{"line":36,"column":23},"end":{"line":36,"column":34}}},"6":{"name":"(anonymous_6)","line":55,"loc":{"start":{"line":55,"column":25},"end":{"line":55,"column":38}}},"7":{"name":"done","line":62,"loc":{"start":{"line":62,"column":0},"end":{"line":62,"column":16}}}},"statementMap":{"1":{"start":{"line":3,"column":0},"end":{"line":14,"column":1}},"2":{"start":{"line":4,"column":2},"end":{"line":6,"column":3}},"3":{"start":{"line":5,"column":4},"end":{"line":5,"column":30}},"4":{"start":{"line":8,"column":2},"end":{"line":8,"column":26}},"5":{"start":{"line":9,"column":2},"end":{"line":9,"column":53}},"6":{"start":{"line":10,"column":2},"end":{"line":10,"column":19}},"7":{"start":{"line":11,"column":2},"end":{"line":11,"column":17}},"8":{"start":{"line":12,"column":2},"end":{"line":12,"column":16}},"9":{"start":{"line":13,"column":2},"end":{"line":13,"column":31}},"10":{"start":{"line":16,"column":0},"end":{"line":20,"column":2}},"11":{"start":{"line":22,"column":0},"end":{"line":28,"column":3}},"12":{"start":{"line":23,"column":2},"end":{"line":27,"column":4}},"13":{"start":{"line":24,"column":4},"end":{"line":24,"column":75}},"14":{"start":{"line":25,"column":4},"end":{"line":25,"column":16}},"15":{"start":{"line":26,"column":4},"end":{"line":26,"column":24}},"16":{"start":{"line":30,"column":0},"end":{"line":34,"column":3}},"17":{"start":{"line":32,"column":4},"end":{"line":32,"column":43}},"18":{"start":{"line":36,"column":0},"end":{"line":53,"column":2}},"19":{"start":{"line":37,"column":2},"end":{"line":39,"column":3}},"20":{"start":{"line":38,"column":4},"end":{"line":38,"column":11}},"21":{"start":{"line":40,"column":2},"end":{"line":45,"column":3}},"22":{"start":{"line":41,"column":4},"end":{"line":41,"column":32}},"23":{"start":{"line":42,"column":4},"end":{"line":42,"column":19}},"24":{"start":{"line":43,"column":4},"end":{"line":43,"column":20}},"25":{"start":{"line":44,"column":4},"end":{"line":44,"column":16}},"26":{"start":{"line":47,"column":2},"end":{"line":52,"column":3}},"27":{"start":{"line":48,"column":4},"end":{"line":51,"column":5}},"28":{"start":{"line":49,"column":6},"end":{"line":49,"column":30}},"29":{"start":{"line":50,"column":6},"end":{"line":50,"column":27}},"30":{"start":{"line":55,"column":0},"end":{"line":60,"column":2}},"31":{"start":{"line":56,"column":2},"end":{"line":59,"column":3}},"32":{"start":{"line":57,"column":4},"end":{"line":57,"column":22}},"33":{"start":{"line":58,"column":4},"end":{"line":58,"column":16}},"34":{"start":{"line":62,"column":0},"end":{"line":65,"column":1}},"35":{"start":{"line":63,"column":2},"end":{"line":63,"column":17}},"36":{"start":{"line":64,"column":2},"end":{"line":64,"column":14}},"37":{"start":{"line":67,"column":0},"end":{"line":67,"column":23}}},"branchMap":{"1":{"line":4,"type":"if","locations":[{"start":{"line":4,"column":2},"end":{"line":4,"column":2}},{"start":{"line":4,"column":2},"end":{"line":4,"column":2}}]},"2":{"line":8,"type":"binary-expr","locations":[{"start":{"line":8,"column":12},"end":{"line":8,"column":19}},{"start":{"line":8,"column":23},"end":{"line":8,"column":25}}]},"3":{"line":9,"type":"binary-expr","locations":[{"start":{"line":9,"column":21},"end":{"line":9,"column":40}},{"start":{"line":9,"column":44},"end":{"line":9,"column":52}}]},"4":{"line":37,"type":"if","locations":[{"start":{"line":37,"column":2},"end":{"line":37,"column":2}},{"start":{"line":37,"column":2},"end":{"line":37,"column":2}}]},"5":{"line":40,"type":"if","locations":[{"start":{"line":40,"column":2},"end":{"line":40,"column":2}},{"start":{"line":40,"column":2},"end":{"line":40,"column":2}}]},"6":{"line":47,"type":"if","locations":[{"start":{"line":47,"column":2},"end":{"line":47,"column":2}},{"start":{"line":47,"column":2},"end":{"line":47,"column":2}}]},"7":{"line":56,"type":"if","locations":[{"start":{"line":56,"column":2},"end":{"line":56,"column":2}},{"start":{"line":56,"column":2},"end":{"line":56,"column":2}}]}}}} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html new file mode 100644 index 0000000000000000000000000000000000000000..198882b4b1185be9e2062cc932e325dcad1e5df7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.html @@ -0,0 +1,73 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for async-throttle/</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="../prettify.css"> + <link rel="stylesheet" href="../base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(../sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">async-throttle/</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"><a href="../index.html">All files</a> » async-throttle/</div> +</div> +<div class="body"> +<div class="coverage-summary"> +<table> +<thead> +<tr> + <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> + <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> + <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> + <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> + <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> + <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> + <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> +</tr> +</thead> +<tbody><tr> + <td class="file high" data-value="index.js"><a href="index.js.html">index.js</a></td> + <td data-value="100" class="pic high"><span class="cover-fill cover-full" style="width: 100px;"></span><span class="cover-empty" style="width:0px;"></span></td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + <td data-value="92.86" class="pct high">92.86%</td> + <td data-value="14" class="abs high">(13 / 14)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="7" class="abs high">(7 / 7)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + </tr> + +</tbody> +</table> +</div> +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="../prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="../sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html new file mode 100644 index 0000000000000000000000000000000000000000..adc030fda975915569d2aa614db5d107dfa3aa06 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/async-throttle/index.js.html @@ -0,0 +1,246 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for async-throttle/index.js</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="../prettify.css"> + <link rel="stylesheet" href="../base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(../sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">async-throttle/index.js</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"><a href="../index.html">All files</a> » <a href="index.html">async-throttle/</a> » index.js</div> +</div> +<div class="body"> +<pre><table class="coverage"> +<tr><td class="line-count">1 +2 +3 +4 +5 +6 +7 +8 +9 +10 +11 +12 +13 +14 +15 +16 +17 +18 +19 +20 +21 +22 +23 +24 +25 +26 +27 +28 +29 +30 +31 +32 +33 +34 +35 +36 +37 +38 +39 +40 +41 +42 +43 +44 +45 +46 +47 +48 +49 +50 +51 +52 +53 +54 +55 +56 +57 +58 +59 +60 +61 +62 +63 +64 +65 +66 +67 +68</td><td class="line-coverage"><span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">7</span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">3</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">19</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">45</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">39</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">39</span> +<span class="cline-any cline-yes">18</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-yes">6</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-yes">13</span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-neutral"> </span> +<span class="cline-any cline-yes">1</span> +<span class="cline-any cline-neutral"> </span></td><td class="text"><pre class="prettyprint lang-js">'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + <span class="missing-if-branch" title="else path not taken" >E</span>if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; + </pre></td></tr> +</table></pre> + +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="../prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="../sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/base.css b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/base.css new file mode 100644 index 0000000000000000000000000000000000000000..a6a2f3284d0221eee83373df7f9ba792601efe51 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/base.css @@ -0,0 +1,182 @@ +body, html { + margin:0; padding: 0; +} +body { + font-family: Helvetica Neue, Helvetica,Arial; + font-size: 10pt; +} +div.header, div.footer { + background: #eee; + padding: 1em; +} +div.header { + z-index: 100; + position: fixed; + top: 0; + border-bottom: 1px solid #666; + width: 100%; +} +div.footer { + border-top: 1px solid #666; +} +div.body { + margin-top: 10em; +} +div.meta { + font-size: 90%; + text-align: center; +} +h1, h2, h3 { + font-weight: normal; +} +h1 { + font-size: 12pt; +} +h2 { + font-size: 10pt; +} +pre { + font-family: Consolas, Menlo, Monaco, monospace; + margin: 0; + padding: 0; + line-height: 1.3; + font-size: 14px; + -moz-tab-size: 2; + -o-tab-size: 2; + tab-size: 2; +} + +div.path { font-size: 110%; } +div.path a:link, div.path a:visited { color: #000; } +table.coverage { border-collapse: collapse; margin:0; padding: 0 } + +table.coverage td { + margin: 0; + padding: 0; + color: #111; + vertical-align: top; +} +table.coverage td.line-count { + width: 50px; + text-align: right; + padding-right: 5px; +} +table.coverage td.line-coverage { + color: #777 !important; + text-align: right; + border-left: 1px solid #666; + border-right: 1px solid #666; +} + +table.coverage td.text { +} + +table.coverage td span.cline-any { + display: inline-block; + padding: 0 5px; + width: 40px; +} +table.coverage td span.cline-neutral { + background: #eee; +} +table.coverage td span.cline-yes { + background: #b5d592; + color: #999; +} +table.coverage td span.cline-no { + background: #fc8c84; +} + +.cstat-yes { color: #111; } +.cstat-no { background: #fc8c84; color: #111; } +.fstat-no { background: #ffc520; color: #111 !important; } +.cbranch-no { background: yellow !important; color: #111; } + +.cstat-skip { background: #ddd; color: #111; } +.fstat-skip { background: #ddd; color: #111 !important; } +.cbranch-skip { background: #ddd !important; color: #111; } + +.missing-if-branch { + display: inline-block; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: black; + color: yellow; +} + +.skip-if-branch { + display: none; + margin-right: 10px; + position: relative; + padding: 0 4px; + background: #ccc; + color: white; +} + +.missing-if-branch .typ, .skip-if-branch .typ { + color: inherit !important; +} + +.entity, .metric { font-weight: bold; } +.metric { display: inline-block; border: 1px solid #333; padding: 0.3em; background: white; } +.metric small { font-size: 80%; font-weight: normal; color: #666; } + +div.coverage-summary table { border-collapse: collapse; margin: 3em; font-size: 110%; } +div.coverage-summary td, div.coverage-summary table th { margin: 0; padding: 0.25em 1em; border-top: 1px solid #666; border-bottom: 1px solid #666; } +div.coverage-summary th { text-align: left; border: 1px solid #666; background: #eee; font-weight: normal; } +div.coverage-summary th.file { border-right: none !important; } +div.coverage-summary th.pic { border-left: none !important; text-align: right; } +div.coverage-summary th.pct { border-right: none !important; } +div.coverage-summary th.abs { border-left: none !important; text-align: right; } +div.coverage-summary td.pct { text-align: right; border-left: 1px solid #666; } +div.coverage-summary td.abs { text-align: right; font-size: 90%; color: #444; border-right: 1px solid #666; } +div.coverage-summary td.file { border-left: 1px solid #666; white-space: nowrap; } +div.coverage-summary td.pic { min-width: 120px !important; } +div.coverage-summary a:link { text-decoration: none; color: #000; } +div.coverage-summary a:visited { text-decoration: none; color: #777; } +div.coverage-summary a:hover { text-decoration: underline; } +div.coverage-summary tfoot td { border-top: 1px solid #666; } + +div.coverage-summary .sorter { + height: 10px; + width: 7px; + display: inline-block; + margin-left: 0.5em; + background: url(sort-arrow-sprite.png) no-repeat scroll 0 0 transparent; +} +div.coverage-summary .sorted .sorter { + background-position: 0 -20px; +} +div.coverage-summary .sorted-desc .sorter { + background-position: 0 -10px; +} + +.high { background: #b5d592 !important; } +.medium { background: #ffe87c !important; } +.low { background: #fc8c84 !important; } + +span.cover-fill, span.cover-empty { + display:inline-block; + border:1px solid #444; + background: white; + height: 12px; +} +span.cover-fill { + background: #ccc; + border-right: 1px solid #444; +} +span.cover-empty { + background: white; + border-left: none; +} +span.cover-full { + border-right: none !important; +} +pre.prettyprint { + border: none !important; + padding: 0 !important; + margin: 0 !important; +} +.com { color: #999 !important; } +.ignore-none { color: #999; font-weight: normal; } diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/index.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/index.html new file mode 100644 index 0000000000000000000000000000000000000000..782a1cff1190b0c243a453b25316d42a8e0cb63b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/index.html @@ -0,0 +1,73 @@ +<!doctype html> +<html lang="en"> +<head> + <title>Code coverage report for All files</title> + <meta charset="utf-8"> + <link rel="stylesheet" href="prettify.css"> + <link rel="stylesheet" href="base.css"> + <style type='text/css'> + div.coverage-summary .sorter { + background-image: url(sort-arrow-sprite.png); + } + </style> +</head> +<body> +<div class="header high"> + <h1>Code coverage report for <span class="entity">All files</span></h1> + <h2> + Statements: <span class="metric">100% <small>(37 / 37)</small></span> + Branches: <span class="metric">92.86% <small>(13 / 14)</small></span> + Functions: <span class="metric">100% <small>(7 / 7)</small></span> + Lines: <span class="metric">100% <small>(37 / 37)</small></span> + Ignored: <span class="metric"><span class="ignore-none">none</span></span> + </h2> + <div class="path"></div> +</div> +<div class="body"> +<div class="coverage-summary"> +<table> +<thead> +<tr> + <th data-col="file" data-fmt="html" data-html="true" class="file">File</th> + <th data-col="pic" data-type="number" data-fmt="html" data-html="true" class="pic"></th> + <th data-col="statements" data-type="number" data-fmt="pct" class="pct">Statements</th> + <th data-col="statements_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="branches" data-type="number" data-fmt="pct" class="pct">Branches</th> + <th data-col="branches_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="functions" data-type="number" data-fmt="pct" class="pct">Functions</th> + <th data-col="functions_raw" data-type="number" data-fmt="html" class="abs"></th> + <th data-col="lines" data-type="number" data-fmt="pct" class="pct">Lines</th> + <th data-col="lines_raw" data-type="number" data-fmt="html" class="abs"></th> +</tr> +</thead> +<tbody><tr> + <td class="file high" data-value="async-throttle/"><a href="async-throttle/index.html">async-throttle/</a></td> + <td data-value="100" class="pic high"><span class="cover-fill cover-full" style="width: 100px;"></span><span class="cover-empty" style="width:0px;"></span></td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + <td data-value="92.86" class="pct high">92.86%</td> + <td data-value="14" class="abs high">(13 / 14)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="7" class="abs high">(7 / 7)</td> + <td data-value="100" class="pct high">100%</td> + <td data-value="37" class="abs high">(37 / 37)</td> + </tr> + +</tbody> +</table> +</div> +</div> +<div class="footer"> + <div class="meta">Generated by <a href="http://istanbul-js.org/" target="_blank">istanbul</a> at Mon Sep 11 2017 11:14:14 GMT-0500 (CDT)</div> +</div> +<script src="prettify.js"></script> +<script> +window.onload = function () { + if (typeof prettyPrint === 'function') { + prettyPrint(); + } +}; +</script> +<script src="sorter.js"></script> +</body> +</html> diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css new file mode 100644 index 0000000000000000000000000000000000000000..b317a7cda31a440fbd47540297ee3c68d51f343e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.css @@ -0,0 +1 @@ +.pln{color:#000}@media screen{.str{color:#080}.kwd{color:#008}.com{color:#800}.typ{color:#606}.lit{color:#066}.pun,.opn,.clo{color:#660}.tag{color:#008}.atn{color:#606}.atv{color:#080}.dec,.var{color:#606}.fun{color:red}}@media print,projection{.str{color:#060}.kwd{color:#006;font-weight:bold}.com{color:#600;font-style:italic}.typ{color:#404;font-weight:bold}.lit{color:#044}.pun,.opn,.clo{color:#440}.tag{color:#006;font-weight:bold}.atn{color:#404}.atv{color:#060}}pre.prettyprint{padding:2px;border:1px solid #888}ol.linenums{margin-top:0;margin-bottom:0}li.L0,li.L1,li.L2,li.L3,li.L5,li.L6,li.L7,li.L8{list-style-type:none}li.L1,li.L3,li.L5,li.L7,li.L9{background:#eee} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js new file mode 100644 index 0000000000000000000000000000000000000000..ef51e03866898f709d2bed6f55ed10bfb9840e6f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/prettify.js @@ -0,0 +1 @@ +window.PR_SHOULD_USE_CONTINUATION=true;(function(){var h=["break,continue,do,else,for,if,return,while"];var u=[h,"auto,case,char,const,default,double,enum,extern,float,goto,int,long,register,short,signed,sizeof,static,struct,switch,typedef,union,unsigned,void,volatile"];var p=[u,"catch,class,delete,false,import,new,operator,private,protected,public,this,throw,true,try,typeof"];var l=[p,"alignof,align_union,asm,axiom,bool,concept,concept_map,const_cast,constexpr,decltype,dynamic_cast,explicit,export,friend,inline,late_check,mutable,namespace,nullptr,reinterpret_cast,static_assert,static_cast,template,typeid,typename,using,virtual,where"];var x=[p,"abstract,boolean,byte,extends,final,finally,implements,import,instanceof,null,native,package,strictfp,super,synchronized,throws,transient"];var R=[x,"as,base,by,checked,decimal,delegate,descending,dynamic,event,fixed,foreach,from,group,implicit,in,interface,internal,into,is,lock,object,out,override,orderby,params,partial,readonly,ref,sbyte,sealed,stackalloc,string,select,uint,ulong,unchecked,unsafe,ushort,var"];var r="all,and,by,catch,class,else,extends,false,finally,for,if,in,is,isnt,loop,new,no,not,null,of,off,on,or,return,super,then,true,try,unless,until,when,while,yes";var w=[p,"debugger,eval,export,function,get,null,set,undefined,var,with,Infinity,NaN"];var s="caller,delete,die,do,dump,elsif,eval,exit,foreach,for,goto,if,import,last,local,my,next,no,our,print,package,redo,require,sub,undef,unless,until,use,wantarray,while,BEGIN,END";var I=[h,"and,as,assert,class,def,del,elif,except,exec,finally,from,global,import,in,is,lambda,nonlocal,not,or,pass,print,raise,try,with,yield,False,True,None"];var f=[h,"alias,and,begin,case,class,def,defined,elsif,end,ensure,false,in,module,next,nil,not,or,redo,rescue,retry,self,super,then,true,undef,unless,until,when,yield,BEGIN,END"];var H=[h,"case,done,elif,esac,eval,fi,function,in,local,set,then,until"];var A=[l,R,w,s+I,f,H];var e=/^(DIR|FILE|vector|(de|priority_)?queue|list|stack|(const_)?iterator|(multi)?(set|map)|bitset|u?(int|float)\d*)/;var C="str";var z="kwd";var j="com";var O="typ";var G="lit";var L="pun";var F="pln";var m="tag";var E="dec";var J="src";var P="atn";var n="atv";var N="nocode";var M="(?:^^\\.?|[+-]|\\!|\\!=|\\!==|\\#|\\%|\\%=|&|&&|&&=|&=|\\(|\\*|\\*=|\\+=|\\,|\\-=|\\->|\\/|\\/=|:|::|\\;|<|<<|<<=|<=|=|==|===|>|>=|>>|>>=|>>>|>>>=|\\?|\\@|\\[|\\^|\\^=|\\^\\^|\\^\\^=|\\{|\\||\\|=|\\|\\||\\|\\|=|\\~|break|case|continue|delete|do|else|finally|instanceof|return|throw|try|typeof)\\s*";function k(Z){var ad=0;var S=false;var ac=false;for(var V=0,U=Z.length;V<U;++V){var ae=Z[V];if(ae.ignoreCase){ac=true}else{if(/[a-z]/i.test(ae.source.replace(/\\u[0-9a-f]{4}|\\x[0-9a-f]{2}|\\[^ux]/gi,""))){S=true;ac=false;break}}}var Y={b:8,t:9,n:10,v:11,f:12,r:13};function ab(ah){var ag=ah.charCodeAt(0);if(ag!==92){return ag}var af=ah.charAt(1);ag=Y[af];if(ag){return ag}else{if("0"<=af&&af<="7"){return parseInt(ah.substring(1),8)}else{if(af==="u"||af==="x"){return parseInt(ah.substring(2),16)}else{return ah.charCodeAt(1)}}}}function T(af){if(af<32){return(af<16?"\\x0":"\\x")+af.toString(16)}var ag=String.fromCharCode(af);if(ag==="\\"||ag==="-"||ag==="["||ag==="]"){ag="\\"+ag}return ag}function X(am){var aq=am.substring(1,am.length-1).match(new RegExp("\\\\u[0-9A-Fa-f]{4}|\\\\x[0-9A-Fa-f]{2}|\\\\[0-3][0-7]{0,2}|\\\\[0-7]{1,2}|\\\\[\\s\\S]|-|[^-\\\\]","g"));var ak=[];var af=[];var ao=aq[0]==="^";for(var ar=ao?1:0,aj=aq.length;ar<aj;++ar){var ah=aq[ar];if(/\\[bdsw]/i.test(ah)){ak.push(ah)}else{var ag=ab(ah);var al;if(ar+2<aj&&"-"===aq[ar+1]){al=ab(aq[ar+2]);ar+=2}else{al=ag}af.push([ag,al]);if(!(al<65||ag>122)){if(!(al<65||ag>90)){af.push([Math.max(65,ag)|32,Math.min(al,90)|32])}if(!(al<97||ag>122)){af.push([Math.max(97,ag)&~32,Math.min(al,122)&~32])}}}}af.sort(function(av,au){return(av[0]-au[0])||(au[1]-av[1])});var ai=[];var ap=[NaN,NaN];for(var ar=0;ar<af.length;++ar){var at=af[ar];if(at[0]<=ap[1]+1){ap[1]=Math.max(ap[1],at[1])}else{ai.push(ap=at)}}var an=["["];if(ao){an.push("^")}an.push.apply(an,ak);for(var ar=0;ar<ai.length;++ar){var at=ai[ar];an.push(T(at[0]));if(at[1]>at[0]){if(at[1]+1>at[0]){an.push("-")}an.push(T(at[1]))}}an.push("]");return an.join("")}function W(al){var aj=al.source.match(new RegExp("(?:\\[(?:[^\\x5C\\x5D]|\\\\[\\s\\S])*\\]|\\\\u[A-Fa-f0-9]{4}|\\\\x[A-Fa-f0-9]{2}|\\\\[0-9]+|\\\\[^ux0-9]|\\(\\?[:!=]|[\\(\\)\\^]|[^\\x5B\\x5C\\(\\)\\^]+)","g"));var ah=aj.length;var an=[];for(var ak=0,am=0;ak<ah;++ak){var ag=aj[ak];if(ag==="("){++am}else{if("\\"===ag.charAt(0)){var af=+ag.substring(1);if(af&&af<=am){an[af]=-1}}}}for(var ak=1;ak<an.length;++ak){if(-1===an[ak]){an[ak]=++ad}}for(var ak=0,am=0;ak<ah;++ak){var ag=aj[ak];if(ag==="("){++am;if(an[am]===undefined){aj[ak]="(?:"}}else{if("\\"===ag.charAt(0)){var af=+ag.substring(1);if(af&&af<=am){aj[ak]="\\"+an[am]}}}}for(var ak=0,am=0;ak<ah;++ak){if("^"===aj[ak]&&"^"!==aj[ak+1]){aj[ak]=""}}if(al.ignoreCase&&S){for(var ak=0;ak<ah;++ak){var ag=aj[ak];var ai=ag.charAt(0);if(ag.length>=2&&ai==="["){aj[ak]=X(ag)}else{if(ai!=="\\"){aj[ak]=ag.replace(/[a-zA-Z]/g,function(ao){var ap=ao.charCodeAt(0);return"["+String.fromCharCode(ap&~32,ap|32)+"]"})}}}}return aj.join("")}var aa=[];for(var V=0,U=Z.length;V<U;++V){var ae=Z[V];if(ae.global||ae.multiline){throw new Error(""+ae)}aa.push("(?:"+W(ae)+")")}return new RegExp(aa.join("|"),ac?"gi":"g")}function a(V){var U=/(?:^|\s)nocode(?:\s|$)/;var X=[];var T=0;var Z=[];var W=0;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=document.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Y=S&&"pre"===S.substring(0,3);function aa(ab){switch(ab.nodeType){case 1:if(U.test(ab.className)){return}for(var ae=ab.firstChild;ae;ae=ae.nextSibling){aa(ae)}var ad=ab.nodeName;if("BR"===ad||"LI"===ad){X[W]="\n";Z[W<<1]=T++;Z[(W++<<1)|1]=ab}break;case 3:case 4:var ac=ab.nodeValue;if(ac.length){if(!Y){ac=ac.replace(/[ \t\r\n]+/g," ")}else{ac=ac.replace(/\r\n?/g,"\n")}X[W]=ac;Z[W<<1]=T;T+=ac.length;Z[(W++<<1)|1]=ab}break}}aa(V);return{sourceCode:X.join("").replace(/\n$/,""),spans:Z}}function B(S,U,W,T){if(!U){return}var V={sourceCode:U,basePos:S};W(V);T.push.apply(T,V.decorations)}var v=/\S/;function o(S){var V=undefined;for(var U=S.firstChild;U;U=U.nextSibling){var T=U.nodeType;V=(T===1)?(V?S:U):(T===3)?(v.test(U.nodeValue)?S:V):V}return V===S?undefined:V}function g(U,T){var S={};var V;(function(){var ad=U.concat(T);var ah=[];var ag={};for(var ab=0,Z=ad.length;ab<Z;++ab){var Y=ad[ab];var ac=Y[3];if(ac){for(var ae=ac.length;--ae>=0;){S[ac.charAt(ae)]=Y}}var af=Y[1];var aa=""+af;if(!ag.hasOwnProperty(aa)){ah.push(af);ag[aa]=null}}ah.push(/[\0-\uffff]/);V=k(ah)})();var X=T.length;var W=function(ah){var Z=ah.sourceCode,Y=ah.basePos;var ad=[Y,F];var af=0;var an=Z.match(V)||[];var aj={};for(var ae=0,aq=an.length;ae<aq;++ae){var ag=an[ae];var ap=aj[ag];var ai=void 0;var am;if(typeof ap==="string"){am=false}else{var aa=S[ag.charAt(0)];if(aa){ai=ag.match(aa[1]);ap=aa[0]}else{for(var ao=0;ao<X;++ao){aa=T[ao];ai=ag.match(aa[1]);if(ai){ap=aa[0];break}}if(!ai){ap=F}}am=ap.length>=5&&"lang-"===ap.substring(0,5);if(am&&!(ai&&typeof ai[1]==="string")){am=false;ap=J}if(!am){aj[ag]=ap}}var ab=af;af+=ag.length;if(!am){ad.push(Y+ab,ap)}else{var al=ai[1];var ak=ag.indexOf(al);var ac=ak+al.length;if(ai[2]){ac=ag.length-ai[2].length;ak=ac-al.length}var ar=ap.substring(5);B(Y+ab,ag.substring(0,ak),W,ad);B(Y+ab+ak,al,q(ar,al),ad);B(Y+ab+ac,ag.substring(ac),W,ad)}}ah.decorations=ad};return W}function i(T){var W=[],S=[];if(T.tripleQuotedStrings){W.push([C,/^(?:\'\'\'(?:[^\'\\]|\\[\s\S]|\'{1,2}(?=[^\']))*(?:\'\'\'|$)|\"\"\"(?:[^\"\\]|\\[\s\S]|\"{1,2}(?=[^\"]))*(?:\"\"\"|$)|\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$))/,null,"'\""])}else{if(T.multiLineStrings){W.push([C,/^(?:\'(?:[^\\\']|\\[\s\S])*(?:\'|$)|\"(?:[^\\\"]|\\[\s\S])*(?:\"|$)|\`(?:[^\\\`]|\\[\s\S])*(?:\`|$))/,null,"'\"`"])}else{W.push([C,/^(?:\'(?:[^\\\'\r\n]|\\.)*(?:\'|$)|\"(?:[^\\\"\r\n]|\\.)*(?:\"|$))/,null,"\"'"])}}if(T.verbatimStrings){S.push([C,/^@\"(?:[^\"]|\"\")*(?:\"|$)/,null])}var Y=T.hashComments;if(Y){if(T.cStyleComments){if(Y>1){W.push([j,/^#(?:##(?:[^#]|#(?!##))*(?:###|$)|.*)/,null,"#"])}else{W.push([j,/^#(?:(?:define|elif|else|endif|error|ifdef|include|ifndef|line|pragma|undef|warning)\b|[^\r\n]*)/,null,"#"])}S.push([C,/^<(?:(?:(?:\.\.\/)*|\/?)(?:[\w-]+(?:\/[\w-]+)+)?[\w-]+\.h|[a-z]\w*)>/,null])}else{W.push([j,/^#[^\r\n]*/,null,"#"])}}if(T.cStyleComments){S.push([j,/^\/\/[^\r\n]*/,null]);S.push([j,/^\/\*[\s\S]*?(?:\*\/|$)/,null])}if(T.regexLiterals){var X=("/(?=[^/*])(?:[^/\\x5B\\x5C]|\\x5C[\\s\\S]|\\x5B(?:[^\\x5C\\x5D]|\\x5C[\\s\\S])*(?:\\x5D|$))+/");S.push(["lang-regex",new RegExp("^"+M+"("+X+")")])}var V=T.types;if(V){S.push([O,V])}var U=(""+T.keywords).replace(/^ | $/g,"");if(U.length){S.push([z,new RegExp("^(?:"+U.replace(/[\s,]+/g,"|")+")\\b"),null])}W.push([F,/^\s+/,null," \r\n\t\xA0"]);S.push([G,/^@[a-z_$][a-z_$@0-9]*/i,null],[O,/^(?:[@_]?[A-Z]+[a-z][A-Za-z_$@0-9]*|\w+_t\b)/,null],[F,/^[a-z_$][a-z_$@0-9]*/i,null],[G,new RegExp("^(?:0x[a-f0-9]+|(?:\\d(?:_\\d+)*\\d*(?:\\.\\d*)?|\\.\\d\\+)(?:e[+\\-]?\\d+)?)[a-z]*","i"),null,"0123456789"],[F,/^\\[\s\S]?/,null],[L,/^.[^\s\w\.$@\'\"\`\/\#\\]*/,null]);return g(W,S)}var K=i({keywords:A,hashComments:true,cStyleComments:true,multiLineStrings:true,regexLiterals:true});function Q(V,ag){var U=/(?:^|\s)nocode(?:\s|$)/;var ab=/\r\n?|\n/;var ac=V.ownerDocument;var S;if(V.currentStyle){S=V.currentStyle.whiteSpace}else{if(window.getComputedStyle){S=ac.defaultView.getComputedStyle(V,null).getPropertyValue("white-space")}}var Z=S&&"pre"===S.substring(0,3);var af=ac.createElement("LI");while(V.firstChild){af.appendChild(V.firstChild)}var W=[af];function ae(al){switch(al.nodeType){case 1:if(U.test(al.className)){break}if("BR"===al.nodeName){ad(al);if(al.parentNode){al.parentNode.removeChild(al)}}else{for(var an=al.firstChild;an;an=an.nextSibling){ae(an)}}break;case 3:case 4:if(Z){var am=al.nodeValue;var aj=am.match(ab);if(aj){var ai=am.substring(0,aj.index);al.nodeValue=ai;var ah=am.substring(aj.index+aj[0].length);if(ah){var ak=al.parentNode;ak.insertBefore(ac.createTextNode(ah),al.nextSibling)}ad(al);if(!ai){al.parentNode.removeChild(al)}}}break}}function ad(ak){while(!ak.nextSibling){ak=ak.parentNode;if(!ak){return}}function ai(al,ar){var aq=ar?al.cloneNode(false):al;var ao=al.parentNode;if(ao){var ap=ai(ao,1);var an=al.nextSibling;ap.appendChild(aq);for(var am=an;am;am=an){an=am.nextSibling;ap.appendChild(am)}}return aq}var ah=ai(ak.nextSibling,0);for(var aj;(aj=ah.parentNode)&&aj.nodeType===1;){ah=aj}W.push(ah)}for(var Y=0;Y<W.length;++Y){ae(W[Y])}if(ag===(ag|0)){W[0].setAttribute("value",ag)}var aa=ac.createElement("OL");aa.className="linenums";var X=Math.max(0,((ag-1))|0)||0;for(var Y=0,T=W.length;Y<T;++Y){af=W[Y];af.className="L"+((Y+X)%10);if(!af.firstChild){af.appendChild(ac.createTextNode("\xA0"))}aa.appendChild(af)}V.appendChild(aa)}function D(ac){var aj=/\bMSIE\b/.test(navigator.userAgent);var am=/\n/g;var al=ac.sourceCode;var an=al.length;var V=0;var aa=ac.spans;var T=aa.length;var ah=0;var X=ac.decorations;var Y=X.length;var Z=0;X[Y]=an;var ar,aq;for(aq=ar=0;aq<Y;){if(X[aq]!==X[aq+2]){X[ar++]=X[aq++];X[ar++]=X[aq++]}else{aq+=2}}Y=ar;for(aq=ar=0;aq<Y;){var at=X[aq];var ab=X[aq+1];var W=aq+2;while(W+2<=Y&&X[W+1]===ab){W+=2}X[ar++]=at;X[ar++]=ab;aq=W}Y=X.length=ar;var ae=null;while(ah<T){var af=aa[ah];var S=aa[ah+2]||an;var ag=X[Z];var ap=X[Z+2]||an;var W=Math.min(S,ap);var ak=aa[ah+1];var U;if(ak.nodeType!==1&&(U=al.substring(V,W))){if(aj){U=U.replace(am,"\r")}ak.nodeValue=U;var ai=ak.ownerDocument;var ao=ai.createElement("SPAN");ao.className=X[Z+1];var ad=ak.parentNode;ad.replaceChild(ao,ak);ao.appendChild(ak);if(V<S){aa[ah+1]=ak=ai.createTextNode(al.substring(W,S));ad.insertBefore(ak,ao.nextSibling)}}V=W;if(V>=S){ah+=2}if(V>=ap){Z+=2}}}var t={};function c(U,V){for(var S=V.length;--S>=0;){var T=V[S];if(!t.hasOwnProperty(T)){t[T]=U}else{if(window.console){console.warn("cannot override language handler %s",T)}}}}function q(T,S){if(!(T&&t.hasOwnProperty(T))){T=/^\s*</.test(S)?"default-markup":"default-code"}return t[T]}c(K,["default-code"]);c(g([],[[F,/^[^<?]+/],[E,/^<!\w[^>]*(?:>|$)/],[j,/^<\!--[\s\S]*?(?:-\->|$)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],[L,/^(?:<[%?]|[%?]>)/],["lang-",/^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-js",/^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i]]),["default-markup","htm","html","mxml","xhtml","xml","xsl"]);c(g([[F,/^[\s]+/,null," \t\r\n"],[n,/^(?:\"[^\"]*\"?|\'[^\']*\'?)/,null,"\"'"]],[[m,/^^<\/?[a-z](?:[\w.:-]*\w)?|\/?>$/i],[P,/^(?!style[\s=]|on)[a-z](?:[\w:-]*\w)?/i],["lang-uq.val",/^=\s*([^>\'\"\s]*(?:[^>\'\"\s\/]|\/(?=\s)))/],[L,/^[=<>\/]+/],["lang-js",/^on\w+\s*=\s*\"([^\"]+)\"/i],["lang-js",/^on\w+\s*=\s*\'([^\']+)\'/i],["lang-js",/^on\w+\s*=\s*([^\"\'>\s]+)/i],["lang-css",/^style\s*=\s*\"([^\"]+)\"/i],["lang-css",/^style\s*=\s*\'([^\']+)\'/i],["lang-css",/^style\s*=\s*([^\"\'>\s]+)/i]]),["in.tag"]);c(g([],[[n,/^[\s\S]+/]]),["uq.val"]);c(i({keywords:l,hashComments:true,cStyleComments:true,types:e}),["c","cc","cpp","cxx","cyc","m"]);c(i({keywords:"null,true,false"}),["json"]);c(i({keywords:R,hashComments:true,cStyleComments:true,verbatimStrings:true,types:e}),["cs"]);c(i({keywords:x,cStyleComments:true}),["java"]);c(i({keywords:H,hashComments:true,multiLineStrings:true}),["bsh","csh","sh"]);c(i({keywords:I,hashComments:true,multiLineStrings:true,tripleQuotedStrings:true}),["cv","py"]);c(i({keywords:s,hashComments:true,multiLineStrings:true,regexLiterals:true}),["perl","pl","pm"]);c(i({keywords:f,hashComments:true,multiLineStrings:true,regexLiterals:true}),["rb"]);c(i({keywords:w,cStyleComments:true,regexLiterals:true}),["js"]);c(i({keywords:r,hashComments:3,cStyleComments:true,multilineStrings:true,tripleQuotedStrings:true,regexLiterals:true}),["coffee"]);c(g([],[[C,/^[\s\S]+/]]),["regex"]);function d(V){var U=V.langExtension;try{var S=a(V.sourceNode);var T=S.sourceCode;V.sourceCode=T;V.spans=S.spans;V.basePos=0;q(U,T)(V);D(V)}catch(W){if("console" in window){console.log(W&&W.stack?W.stack:W)}}}function y(W,V,U){var S=document.createElement("PRE");S.innerHTML=W;if(U){Q(S,U)}var T={langExtension:V,numberLines:U,sourceNode:S};d(T);return S.innerHTML}function b(ad){function Y(af){return document.getElementsByTagName(af)}var ac=[Y("pre"),Y("code"),Y("xmp")];var T=[];for(var aa=0;aa<ac.length;++aa){for(var Z=0,V=ac[aa].length;Z<V;++Z){T.push(ac[aa][Z])}}ac=null;var W=Date;if(!W.now){W={now:function(){return +(new Date)}}}var X=0;var S;var ab=/\blang(?:uage)?-([\w.]+)(?!\S)/;var ae=/\bprettyprint\b/;function U(){var ag=(window.PR_SHOULD_USE_CONTINUATION?W.now()+250:Infinity);for(;X<T.length&&W.now()<ag;X++){var aj=T[X];var ai=aj.className;if(ai.indexOf("prettyprint")>=0){var ah=ai.match(ab);var am;if(!ah&&(am=o(aj))&&"CODE"===am.tagName){ah=am.className.match(ab)}if(ah){ah=ah[1]}var al=false;for(var ak=aj.parentNode;ak;ak=ak.parentNode){if((ak.tagName==="pre"||ak.tagName==="code"||ak.tagName==="xmp")&&ak.className&&ak.className.indexOf("prettyprint")>=0){al=true;break}}if(!al){var af=aj.className.match(/\blinenums\b(?::(\d+))?/);af=af?af[1]&&af[1].length?+af[1]:true:false;if(af){Q(aj,af)}S={langExtension:ah,sourceNode:aj,numberLines:af};d(S)}}}if(X<T.length){setTimeout(U,250)}else{if(ad){ad()}}}U()}window.prettyPrintOne=y;window.prettyPrint=b;window.PR={createSimpleLexer:g,registerLangHandler:c,sourceDecorator:i,PR_ATTRIB_NAME:P,PR_ATTRIB_VALUE:n,PR_COMMENT:j,PR_DECLARATION:E,PR_KEYWORD:z,PR_LITERAL:G,PR_NOCODE:N,PR_PLAIN:F,PR_PUNCTUATION:L,PR_SOURCE:J,PR_STRING:C,PR_TAG:m,PR_TYPE:O}})();PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_DECLARATION,/^<!\w[^>]*(?:>|$)/],[PR.PR_COMMENT,/^<\!--[\s\S]*?(?:-\->|$)/],[PR.PR_PUNCTUATION,/^(?:<[%?]|[%?]>)/],["lang-",/^<\?([\s\S]+?)(?:\?>|$)/],["lang-",/^<%([\s\S]+?)(?:%>|$)/],["lang-",/^<xmp\b[^>]*>([\s\S]+?)<\/xmp\b[^>]*>/i],["lang-handlebars",/^<script\b[^>]*type\s*=\s*['"]?text\/x-handlebars-template['"]?\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-js",/^<script\b[^>]*>([\s\S]*?)(<\/script\b[^>]*>)/i],["lang-css",/^<style\b[^>]*>([\s\S]*?)(<\/style\b[^>]*>)/i],["lang-in.tag",/^(<\/?[a-z][^<>]*>)/i],[PR.PR_DECLARATION,/^{{[#^>/]?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{&?\s*[\w.][^}]*}}/],[PR.PR_DECLARATION,/^{{{>?\s*[\w.][^}]*}}}/],[PR.PR_COMMENT,/^{{![^}]*}}/]]),["handlebars","hbs"]);PR.registerLangHandler(PR.createSimpleLexer([[PR.PR_PLAIN,/^[ \t\r\n\f]+/,null," \t\r\n\f"]],[[PR.PR_STRING,/^\"(?:[^\n\r\f\\\"]|\\(?:\r\n?|\n|\f)|\\[\s\S])*\"/,null],[PR.PR_STRING,/^\'(?:[^\n\r\f\\\']|\\(?:\r\n?|\n|\f)|\\[\s\S])*\'/,null],["lang-css-str",/^url\(([^\)\"\']*)\)/i],[PR.PR_KEYWORD,/^(?:url|rgb|\!important|@import|@page|@media|@charset|inherit)(?=[^\-\w]|$)/i,null],["lang-css-kw",/^(-?(?:[_a-z]|(?:\\[0-9a-f]+ ?))(?:[_a-z0-9\-]|\\(?:\\[0-9a-f]+ ?))*)\s*:/i],[PR.PR_COMMENT,/^\/\*[^*]*\*+(?:[^\/*][^*]*\*+)*\//],[PR.PR_COMMENT,/^(?:<!--|-->)/],[PR.PR_LITERAL,/^(?:\d+|\d*\.\d+)(?:%|[a-z]+)?/i],[PR.PR_LITERAL,/^#(?:[0-9a-f]{3}){1,2}/i],[PR.PR_PLAIN,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i],[PR.PR_PUNCTUATION,/^[^\s\w\'\"]+/]]),["css"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_KEYWORD,/^-?(?:[_a-z]|(?:\\[\da-f]+ ?))(?:[_a-z\d\-]|\\(?:\\[\da-f]+ ?))*/i]]),["css-kw"]);PR.registerLangHandler(PR.createSimpleLexer([],[[PR.PR_STRING,/^[^\)\"\']+/]]),["css-str"]); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png new file mode 100644 index 0000000000000000000000000000000000000000..03f704a609c6fd0dbfdac63466a7d7c958b5cbf3 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sort-arrow-sprite.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js new file mode 100644 index 0000000000000000000000000000000000000000..6afb736c39fb15da83c56b083ab88b505c247a38 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov-report/sorter.js @@ -0,0 +1,156 @@ +var addSorting = (function () { + "use strict"; + var cols, + currentSort = { + index: 0, + desc: false + }; + + // returns the summary table element + function getTable() { return document.querySelector('.coverage-summary table'); } + // returns the thead element of the summary table + function getTableHeader() { return getTable().querySelector('thead tr'); } + // returns the tbody element of the summary table + function getTableBody() { return getTable().querySelector('tbody'); } + // returns the th element for nth column + function getNthColumn(n) { return getTableHeader().querySelectorAll('th')[n]; } + + // loads all columns + function loadColumns() { + var colNodes = getTableHeader().querySelectorAll('th'), + colNode, + cols = [], + col, + i; + + for (i = 0; i < colNodes.length; i += 1) { + colNode = colNodes[i]; + col = { + key: colNode.getAttribute('data-col'), + sortable: !colNode.getAttribute('data-nosort'), + type: colNode.getAttribute('data-type') || 'string' + }; + cols.push(col); + if (col.sortable) { + col.defaultDescSort = col.type === 'number'; + colNode.innerHTML = colNode.innerHTML + '<span class="sorter"></span>'; + } + } + return cols; + } + // attaches a data attribute to every tr element with an object + // of data values keyed by column name + function loadRowData(tableRow) { + var tableCols = tableRow.querySelectorAll('td'), + colNode, + col, + data = {}, + i, + val; + for (i = 0; i < tableCols.length; i += 1) { + colNode = tableCols[i]; + col = cols[i]; + val = colNode.getAttribute('data-value'); + if (col.type === 'number') { + val = Number(val); + } + data[col.key] = val; + } + return data; + } + // loads all row data + function loadData() { + var rows = getTableBody().querySelectorAll('tr'), + i; + + for (i = 0; i < rows.length; i += 1) { + rows[i].data = loadRowData(rows[i]); + } + } + // sorts the table using the data for the ith column + function sortByIndex(index, desc) { + var key = cols[index].key, + sorter = function (a, b) { + a = a.data[key]; + b = b.data[key]; + return a < b ? -1 : a > b ? 1 : 0; + }, + finalSorter = sorter, + tableBody = document.querySelector('.coverage-summary tbody'), + rowNodes = tableBody.querySelectorAll('tr'), + rows = [], + i; + + if (desc) { + finalSorter = function (a, b) { + return -1 * sorter(a, b); + }; + } + + for (i = 0; i < rowNodes.length; i += 1) { + rows.push(rowNodes[i]); + tableBody.removeChild(rowNodes[i]); + } + + rows.sort(finalSorter); + + for (i = 0; i < rows.length; i += 1) { + tableBody.appendChild(rows[i]); + } + } + // removes sort indicators for current column being sorted + function removeSortIndicators() { + var col = getNthColumn(currentSort.index), + cls = col.className; + + cls = cls.replace(/ sorted$/, '').replace(/ sorted-desc$/, ''); + col.className = cls; + } + // adds sort indicators for current column being sorted + function addSortIndicators() { + getNthColumn(currentSort.index).className += currentSort.desc ? ' sorted-desc' : ' sorted'; + } + // adds event listeners for all sorter widgets + function enableUI() { + var i, + el, + ithSorter = function ithSorter(i) { + var col = cols[i]; + + return function () { + var desc = col.defaultDescSort; + + if (currentSort.index === i) { + desc = !currentSort.desc; + } + sortByIndex(i, desc); + removeSortIndicators(); + currentSort.index = i; + currentSort.desc = desc; + addSortIndicators(); + }; + }; + for (i =0 ; i < cols.length; i += 1) { + if (cols[i].sortable) { + el = getNthColumn(i).querySelector('.sorter'); + if (el.addEventListener) { + el.addEventListener('click', ithSorter(i)); + } else { + el.attachEvent('onclick', ithSorter(i)); + } + } + } + } + // adds sorting functionality to the UI + return function () { + if (!getTable()) { + return; + } + cols = loadColumns(); + loadData(cols); + addSortIndicators(); + enableUI(); + }; +})(); + +window.addEventListener('load', addSorting); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov.info b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov.info new file mode 100644 index 0000000000000000000000000000000000000000..fbf36aab035770e2b116084456e1367e9506b090 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/coverage/lcov.info @@ -0,0 +1,74 @@ +TN: +SF:/Users/samuelreed/git/forks/async-throttle/index.js +FN:3,Queue +FN:22,(anonymous_2) +FN:23,(anonymous_3) +FN:31,(anonymous_4) +FN:36,(anonymous_5) +FN:55,(anonymous_6) +FN:62,done +FNF:7 +FNH:7 +FNDA:7,Queue +FNDA:3,(anonymous_2) +FNDA:13,(anonymous_3) +FNDA:19,(anonymous_4) +FNDA:45,(anonymous_5) +FNDA:6,(anonymous_6) +FNDA:13,done +DA:3,1 +DA:4,7 +DA:5,1 +DA:8,6 +DA:9,6 +DA:10,6 +DA:11,6 +DA:12,6 +DA:13,6 +DA:16,1 +DA:22,1 +DA:23,3 +DA:24,13 +DA:25,13 +DA:26,13 +DA:30,1 +DA:32,19 +DA:36,1 +DA:37,45 +DA:38,6 +DA:40,39 +DA:41,13 +DA:42,13 +DA:43,13 +DA:44,13 +DA:47,39 +DA:48,18 +DA:49,6 +DA:50,6 +DA:55,1 +DA:56,6 +DA:57,6 +DA:58,6 +DA:62,1 +DA:63,13 +DA:64,13 +DA:67,1 +LF:37 +LH:37 +BRDA:4,1,0,1 +BRDA:4,1,1,6 +BRDA:8,2,0,6 +BRDA:8,2,1,5 +BRDA:9,3,0,6 +BRDA:9,3,1,5 +BRDA:37,4,0,6 +BRDA:37,4,1,39 +BRDA:40,5,0,13 +BRDA:40,5,1,26 +BRDA:47,6,0,18 +BRDA:47,6,1,21 +BRDA:56,7,0,6 +BRDA:56,7,1,0 +BRF:14 +BRH:13 +end_of_record diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c9bd2f9778213d8adbab4c8a17d13e32aa3fc25b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/index.js @@ -0,0 +1,67 @@ +'use strict'; + +function Queue(options) { + if (!(this instanceof Queue)) { + return new Queue(options); + } + + options = options || {}; + this.concurrency = options.concurrency || Infinity; + this.pending = 0; + this.jobs = []; + this.cbs = []; + this._done = done.bind(this); +} + +var arrayAddMethods = [ + 'push', + 'unshift', + 'splice' +]; + +arrayAddMethods.forEach(function(method) { + Queue.prototype[method] = function() { + var methodResult = Array.prototype[method].apply(this.jobs, arguments); + this._run(); + return methodResult; + }; +}); + +Object.defineProperty(Queue.prototype, 'length', { + get: function() { + return this.pending + this.jobs.length; + } +}); + +Queue.prototype._run = function() { + if (this.pending === this.concurrency) { + return; + } + if (this.jobs.length) { + var job = this.jobs.shift(); + this.pending++; + job(this._done); + this._run(); + } + + if (this.pending === 0) { + while (this.cbs.length !== 0) { + var cb = this.cbs.pop(); + process.nextTick(cb); + } + } +}; + +Queue.prototype.onDone = function(cb) { + if (typeof cb === 'function') { + this.cbs.push(cb); + this._run(); + } +}; + +function done() { + this.pending--; + this._run(); +} + +module.exports = Queue; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/package.json new file mode 100644 index 0000000000000000000000000000000000000000..86e7eb7066857bee439de93ef6c59538ec606790 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/package.json @@ -0,0 +1,69 @@ +{ + "_from": "async-limiter@~1.0.0", + "_id": "async-limiter@1.0.0", + "_inBundle": false, + "_integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==", + "_location": "/async-limiter", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "async-limiter@~1.0.0", + "name": "async-limiter", + "escapedName": "async-limiter", + "rawSpec": "~1.0.0", + "saveSpec": null, + "fetchSpec": "~1.0.0" + }, + "_requiredBy": [ + "/ws" + ], + "_resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "_shasum": "78faed8c3d074ab81f22b4e985d79e8738f720f8", + "_spec": "async-limiter@~1.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/ws", + "author": { + "name": "Samuel Reed" + }, + "bugs": { + "url": "https://github.com/strml/async-limiter/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "asynchronous function queue with adjustable concurrency", + "devDependencies": { + "coveralls": "^2.11.2", + "eslint": "^4.6.1", + "eslint-plugin-mocha": "^4.11.0", + "intelli-espower-loader": "^1.0.1", + "istanbul": "^0.3.2", + "mocha": "^3.5.2", + "power-assert": "^1.4.4" + }, + "homepage": "https://github.com/strml/async-limiter#readme", + "keywords": [ + "throttle", + "async", + "limiter", + "asynchronous", + "job", + "task", + "concurrency", + "concurrent" + ], + "license": "MIT", + "name": "async-limiter", + "repository": { + "type": "git", + "url": "git+https://github.com/strml/async-limiter.git" + }, + "scripts": { + "coverage": "istanbul cover ./node_modules/mocha/bin/_mocha --report lcovonly -- -R spec && cat ./coverage/lcov.info | coveralls", + "example": "node example", + "lint": "eslint .", + "test": "mocha --R intelli-espower-loader test/", + "travis": "npm run lint && npm run coverage" + }, + "version": "1.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/readme.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..dcf4932f9a8cccba8c30a617efbde48c0f93da80 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/async-limiter/readme.md @@ -0,0 +1,132 @@ +# Async-Limiter + +A module for limiting concurrent asynchronous actions in flight. Forked from [queue](https://github.com/jessetane/queue). + +[](http://www.npmjs.org/async-limiter) +[](https://travis-ci.org/STRML/async-limiter) +[](https://coveralls.io/r/STRML/async-limiter) + +This module exports a class `Limiter` that implements some of the `Array` API. +Pass async functions (ones that accept a callback or return a promise) to an instance's additive array methods. + +## Motivation + +Certain functions, like `zlib`, have [undesirable behavior](https://github.com/nodejs/node/issues/8871#issuecomment-250915913) when +run at infinite concurrency. + +In this case, it is actually faster, and takes far less memory, to limit concurrency. + +This module should do the absolute minimum work necessary to queue up functions. PRs are welcome that would +make this module faster or lighter, but new functionality is not desired. + +Style should confirm to nodejs/node style. + +## Example + +``` javascript +var Limiter = require('async-limiter') + +var t = new Limiter({concurrency: 2}); +var results = [] + +// add jobs using the familiar Array API +t.push(function (cb) { + results.push('two') + cb() +}) + +t.push( + function (cb) { + results.push('four') + cb() + }, + function (cb) { + results.push('five') + cb() + } +) + +t.unshift(function (cb) { + results.push('one') + cb() +}) + +t.splice(2, 0, function (cb) { + results.push('three') + cb() +}) + +// Jobs run automatically. If you want a callback when all are done, +// call 'onDone()'. +t.onDone(function () { + console.log('all done:', results) +}) +``` + +## Zlib Example + +```js +const zlib = require('zlib'); +const Limiter = require('async-limiter'); + +const message = {some: "data"}; +const payload = new Buffer(JSON.stringify(message)); + +// Try with different concurrency values to see how this actually +// slows significantly with higher concurrency! +// +// 5: 1398.607ms +// 10: 1375.668ms +// Infinity: 4423.300ms +// +const t = new Limiter({concurrency: 5}); +function deflate(payload, cb) { + t.push(function(done) { + zlib.deflate(payload, function(err, buffer) { + done(); + cb(err, buffer); + }); + }); +} + +console.time('deflate'); +for(let i = 0; i < 30000; ++i) { + deflate(payload, function (err, buffer) {}); +} +q.onDone(function() { + console.timeEnd('deflate'); +}); +``` + +## Install + +`npm install async-limiter` + +## Test + +`npm test` + +## API + +### `var t = new Limiter([opts])` +Constructor. `opts` may contain inital values for: +* `q.concurrency` + +## Instance methods + +### `q.onDone(fn)` +`fn` will be called once and only once, when the queue is empty. + +## Instance methods mixed in from `Array` +Mozilla has docs on how these methods work [here](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array). +### `q.push(element1, ..., elementN)` +### `q.unshift(element1, ..., elementN)` +### `q.splice(index , howMany[, element1[, ...[, elementN]]])` + +## Properties +### `q.concurrency` +Max number of jobs the queue should process concurrently, defaults to `Infinity`. + +### `q.length` +Jobs pending + jobs to process (readonly). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.coveralls.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.coveralls.yml new file mode 100644 index 0000000000000000000000000000000000000000..20a7068581791335487166ddc5001a2ca3a3b060 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.coveralls.yml @@ -0,0 +1 @@ +repo_token: SIAeZjKYlHK74rbcFvNHMUzjRiMpflxve diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.eslintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.eslintrc new file mode 100644 index 0000000000000000000000000000000000000000..8a37ae2c2e5a35db74b4607b4c74e0f4fe39a3e4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.eslintrc @@ -0,0 +1,11 @@ +{ + "env": { + "browser": true, + "node": true + }, + "rules": { + "no-console": 0, + "no-empty": [1, { "allowEmptyCatch": true }] + }, + "extends": "eslint:recommended" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.npmignore b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..5f60eecc84e219e52554407ad38d04abd1cf2111 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.npmignore @@ -0,0 +1,9 @@ +support +test +examples +example +*.sock +dist +yarn.lock +coverage +bower.json diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..6c6090c3b09f2e45d8c0a1dc77ff5f4a81e78a3c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/.travis.yml @@ -0,0 +1,14 @@ + +language: node_js +node_js: + - "6" + - "5" + - "4" + +install: + - make node_modules + +script: + - make lint + - make test + - make coveralls diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..eadaa189517bbcfb2a6784a48ac8d05d2edafe7c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/CHANGELOG.md @@ -0,0 +1,362 @@ + +2.6.9 / 2017-09-22 +================== + + * remove ReDoS regexp in %o formatter (#504) + +2.6.8 / 2017-05-18 +================== + + * Fix: Check for undefined on browser globals (#462, @marbemac) + +2.6.7 / 2017-05-16 +================== + + * Fix: Update ms to 2.0.0 to fix regular expression denial of service vulnerability (#458, @hubdotcom) + * Fix: Inline extend function in node implementation (#452, @dougwilson) + * Docs: Fix typo (#455, @msasad) + +2.6.5 / 2017-04-27 +================== + + * Fix: null reference check on window.documentElement.style.WebkitAppearance (#447, @thebigredgeek) + * Misc: clean up browser reference checks (#447, @thebigredgeek) + * Misc: add npm-debug.log to .gitignore (@thebigredgeek) + + +2.6.4 / 2017-04-20 +================== + + * Fix: bug that would occure if process.env.DEBUG is a non-string value. (#444, @LucianBuzzo) + * Chore: ignore bower.json in npm installations. (#437, @joaovieira) + * Misc: update "ms" to v0.7.3 (@tootallnate) + +2.6.3 / 2017-03-13 +================== + + * Fix: Electron reference to `process.env.DEBUG` (#431, @paulcbetts) + * Docs: Changelog fix (@thebigredgeek) + +2.6.2 / 2017-03-10 +================== + + * Fix: DEBUG_MAX_ARRAY_LENGTH (#420, @slavaGanzin) + * Docs: Add backers and sponsors from Open Collective (#422, @piamancini) + * Docs: Add Slackin invite badge (@tootallnate) + +2.6.1 / 2017-02-10 +================== + + * Fix: Module's `export default` syntax fix for IE8 `Expected identifier` error + * Fix: Whitelist DEBUG_FD for values 1 and 2 only (#415, @pi0) + * Fix: IE8 "Expected identifier" error (#414, @vgoma) + * Fix: Namespaces would not disable once enabled (#409, @musikov) + +2.6.0 / 2016-12-28 +================== + + * Fix: added better null pointer checks for browser useColors (@thebigredgeek) + * Improvement: removed explicit `window.debug` export (#404, @tootallnate) + * Improvement: deprecated `DEBUG_FD` environment variable (#405, @tootallnate) + +2.5.2 / 2016-12-25 +================== + + * Fix: reference error on window within webworkers (#393, @KlausTrainer) + * Docs: fixed README typo (#391, @lurch) + * Docs: added notice about v3 api discussion (@thebigredgeek) + +2.5.1 / 2016-12-20 +================== + + * Fix: babel-core compatibility + +2.5.0 / 2016-12-20 +================== + + * Fix: wrong reference in bower file (@thebigredgeek) + * Fix: webworker compatibility (@thebigredgeek) + * Fix: output formatting issue (#388, @kribblo) + * Fix: babel-loader compatibility (#383, @escwald) + * Misc: removed built asset from repo and publications (@thebigredgeek) + * Misc: moved source files to /src (#378, @yamikuronue) + * Test: added karma integration and replaced babel with browserify for browser tests (#378, @yamikuronue) + * Test: coveralls integration (#378, @yamikuronue) + * Docs: simplified language in the opening paragraph (#373, @yamikuronue) + +2.4.5 / 2016-12-17 +================== + + * Fix: `navigator` undefined in Rhino (#376, @jochenberger) + * Fix: custom log function (#379, @hsiliev) + * Improvement: bit of cleanup + linting fixes (@thebigredgeek) + * Improvement: rm non-maintainted `dist/` dir (#375, @freewil) + * Docs: simplified language in the opening paragraph. (#373, @yamikuronue) + +2.4.4 / 2016-12-14 +================== + + * Fix: work around debug being loaded in preload scripts for electron (#368, @paulcbetts) + +2.4.3 / 2016-12-14 +================== + + * Fix: navigation.userAgent error for react native (#364, @escwald) + +2.4.2 / 2016-12-14 +================== + + * Fix: browser colors (#367, @tootallnate) + * Misc: travis ci integration (@thebigredgeek) + * Misc: added linting and testing boilerplate with sanity check (@thebigredgeek) + +2.4.1 / 2016-12-13 +================== + + * Fix: typo that broke the package (#356) + +2.4.0 / 2016-12-13 +================== + + * Fix: bower.json references unbuilt src entry point (#342, @justmatt) + * Fix: revert "handle regex special characters" (@tootallnate) + * Feature: configurable util.inspect()`options for NodeJS (#327, @tootallnate) + * Feature: %O`(big O) pretty-prints objects (#322, @tootallnate) + * Improvement: allow colors in workers (#335, @botverse) + * Improvement: use same color for same namespace. (#338, @lchenay) + +2.3.3 / 2016-11-09 +================== + + * Fix: Catch `JSON.stringify()` errors (#195, Jovan Alleyne) + * Fix: Returning `localStorage` saved values (#331, Levi Thomason) + * Improvement: Don't create an empty object when no `process` (Nathan Rajlich) + +2.3.2 / 2016-11-09 +================== + + * Fix: be super-safe in index.js as well (@TooTallNate) + * Fix: should check whether process exists (Tom Newby) + +2.3.1 / 2016-11-09 +================== + + * Fix: Added electron compatibility (#324, @paulcbetts) + * Improvement: Added performance optimizations (@tootallnate) + * Readme: Corrected PowerShell environment variable example (#252, @gimre) + * Misc: Removed yarn lock file from source control (#321, @fengmk2) + +2.3.0 / 2016-11-07 +================== + + * Fix: Consistent placement of ms diff at end of output (#215, @gorangajic) + * Fix: Escaping of regex special characters in namespace strings (#250, @zacronos) + * Fix: Fixed bug causing crash on react-native (#282, @vkarpov15) + * Feature: Enabled ES6+ compatible import via default export (#212 @bucaran) + * Feature: Added %O formatter to reflect Chrome's console.log capability (#279, @oncletom) + * Package: Update "ms" to 0.7.2 (#315, @DevSide) + * Package: removed superfluous version property from bower.json (#207 @kkirsche) + * Readme: fix USE_COLORS to DEBUG_COLORS + * Readme: Doc fixes for format string sugar (#269, @mlucool) + * Readme: Updated docs for DEBUG_FD and DEBUG_COLORS environment variables (#232, @mattlyons0) + * Readme: doc fixes for PowerShell (#271 #243, @exoticknight @unreadable) + * Readme: better docs for browser support (#224, @matthewmueller) + * Tooling: Added yarn integration for development (#317, @thebigredgeek) + * Misc: Renamed History.md to CHANGELOG.md (@thebigredgeek) + * Misc: Added license file (#226 #274, @CantemoInternal @sdaitzman) + * Misc: Updated contributors (@thebigredgeek) + +2.2.0 / 2015-05-09 +================== + + * package: update "ms" to v0.7.1 (#202, @dougwilson) + * README: add logging to file example (#193, @DanielOchoa) + * README: fixed a typo (#191, @amir-s) + * browser: expose `storage` (#190, @stephenmathieson) + * Makefile: add a `distclean` target (#189, @stephenmathieson) + +2.1.3 / 2015-03-13 +================== + + * Updated stdout/stderr example (#186) + * Updated example/stdout.js to match debug current behaviour + * Renamed example/stderr.js to stdout.js + * Update Readme.md (#184) + * replace high intensity foreground color for bold (#182, #183) + +2.1.2 / 2015-03-01 +================== + + * dist: recompile + * update "ms" to v0.7.0 + * package: update "browserify" to v9.0.3 + * component: fix "ms.js" repo location + * changed bower package name + * updated documentation about using debug in a browser + * fix: security error on safari (#167, #168, @yields) + +2.1.1 / 2014-12-29 +================== + + * browser: use `typeof` to check for `console` existence + * browser: check for `console.log` truthiness (fix IE 8/9) + * browser: add support for Chrome apps + * Readme: added Windows usage remarks + * Add `bower.json` to properly support bower install + +2.1.0 / 2014-10-15 +================== + + * node: implement `DEBUG_FD` env variable support + * package: update "browserify" to v6.1.0 + * package: add "license" field to package.json (#135, @panuhorsmalahti) + +2.0.0 / 2014-09-01 +================== + + * package: update "browserify" to v5.11.0 + * node: use stderr rather than stdout for logging (#29, @stephenmathieson) + +1.0.4 / 2014-07-15 +================== + + * dist: recompile + * example: remove `console.info()` log usage + * example: add "Content-Type" UTF-8 header to browser example + * browser: place %c marker after the space character + * browser: reset the "content" color via `color: inherit` + * browser: add colors support for Firefox >= v31 + * debug: prefer an instance `log()` function over the global one (#119) + * Readme: update documentation about styled console logs for FF v31 (#116, @wryk) + +1.0.3 / 2014-07-09 +================== + + * Add support for multiple wildcards in namespaces (#122, @seegno) + * browser: fix lint + +1.0.2 / 2014-06-10 +================== + + * browser: update color palette (#113, @gscottolson) + * common: make console logging function configurable (#108, @timoxley) + * node: fix %o colors on old node <= 0.8.x + * Makefile: find node path using shell/which (#109, @timoxley) + +1.0.1 / 2014-06-06 +================== + + * browser: use `removeItem()` to clear localStorage + * browser, node: don't set DEBUG if namespaces is undefined (#107, @leedm777) + * package: add "contributors" section + * node: fix comment typo + * README: list authors + +1.0.0 / 2014-06-04 +================== + + * make ms diff be global, not be scope + * debug: ignore empty strings in enable() + * node: make DEBUG_COLORS able to disable coloring + * *: export the `colors` array + * npmignore: don't publish the `dist` dir + * Makefile: refactor to use browserify + * package: add "browserify" as a dev dependency + * Readme: add Web Inspector Colors section + * node: reset terminal color for the debug content + * node: map "%o" to `util.inspect()` + * browser: map "%j" to `JSON.stringify()` + * debug: add custom "formatters" + * debug: use "ms" module for humanizing the diff + * Readme: add "bash" syntax highlighting + * browser: add Firebug color support + * browser: add colors for WebKit browsers + * node: apply log to `console` + * rewrite: abstract common logic for Node & browsers + * add .jshintrc file + +0.8.1 / 2014-04-14 +================== + + * package: re-add the "component" section + +0.8.0 / 2014-03-30 +================== + + * add `enable()` method for nodejs. Closes #27 + * change from stderr to stdout + * remove unnecessary index.js file + +0.7.4 / 2013-11-13 +================== + + * remove "browserify" key from package.json (fixes something in browserify) + +0.7.3 / 2013-10-30 +================== + + * fix: catch localStorage security error when cookies are blocked (Chrome) + * add debug(err) support. Closes #46 + * add .browser prop to package.json. Closes #42 + +0.7.2 / 2013-02-06 +================== + + * fix package.json + * fix: Mobile Safari (private mode) is broken with debug + * fix: Use unicode to send escape character to shell instead of octal to work with strict mode javascript + +0.7.1 / 2013-02-05 +================== + + * add repository URL to package.json + * add DEBUG_COLORED to force colored output + * add browserify support + * fix component. Closes #24 + +0.7.0 / 2012-05-04 +================== + + * Added .component to package.json + * Added debug.component.js build + +0.6.0 / 2012-03-16 +================== + + * Added support for "-" prefix in DEBUG [Vinay Pulim] + * Added `.enabled` flag to the node version [TooTallNate] + +0.5.0 / 2012-02-02 +================== + + * Added: humanize diffs. Closes #8 + * Added `debug.disable()` to the CS variant + * Removed padding. Closes #10 + * Fixed: persist client-side variant again. Closes #9 + +0.4.0 / 2012-02-01 +================== + + * Added browser variant support for older browsers [TooTallNate] + * Added `debug.enable('project:*')` to browser variant [TooTallNate] + * Added padding to diff (moved it to the right) + +0.3.0 / 2012-01-26 +================== + + * Added millisecond diff when isatty, otherwise UTC string + +0.2.0 / 2012-01-22 +================== + + * Added wildcard support + +0.1.0 / 2011-12-02 +================== + + * Added: remove colors unless stderr isatty [TooTallNate] + +0.0.1 / 2010-01-03 +================== + + * Initial release diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..658c933d28255e8c716899789e8c0f846e5dc125 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/LICENSE @@ -0,0 +1,19 @@ +(The MIT License) + +Copyright (c) 2014 TJ Holowaychuk <tj@vision-media.ca> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..584da8bf938e639ece3ba2bd4105c215c2b1ff51 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/Makefile @@ -0,0 +1,50 @@ +# get Makefile directory name: http://stackoverflow.com/a/5982798/376773 +THIS_MAKEFILE_PATH:=$(word $(words $(MAKEFILE_LIST)),$(MAKEFILE_LIST)) +THIS_DIR:=$(shell cd $(dir $(THIS_MAKEFILE_PATH));pwd) + +# BIN directory +BIN := $(THIS_DIR)/node_modules/.bin + +# Path +PATH := node_modules/.bin:$(PATH) +SHELL := /bin/bash + +# applications +NODE ?= $(shell which node) +YARN ?= $(shell which yarn) +PKG ?= $(if $(YARN),$(YARN),$(NODE) $(shell which npm)) +BROWSERIFY ?= $(NODE) $(BIN)/browserify + +.FORCE: + +install: node_modules + +node_modules: package.json + @NODE_ENV= $(PKG) install + @touch node_modules + +lint: .FORCE + eslint browser.js debug.js index.js node.js + +test-node: .FORCE + istanbul cover node_modules/mocha/bin/_mocha -- test/**.js + +test-browser: .FORCE + mkdir -p dist + + @$(BROWSERIFY) \ + --standalone debug \ + . > dist/debug.js + + karma start --single-run + rimraf dist + +test: .FORCE + concurrently \ + "make test-node" \ + "make test-browser" + +coveralls: + cat ./coverage/lcov.info | ./node_modules/coveralls/bin/coveralls.js + +.PHONY: all install clean distclean diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f67be6b317c19952bb506a9e15e797615eea4533 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/README.md @@ -0,0 +1,312 @@ +# debug +[](https://travis-ci.org/visionmedia/debug) [](https://coveralls.io/github/visionmedia/debug?branch=master) [](https://visionmedia-community-slackin.now.sh/) [](#backers) +[](#sponsors) + + + +A tiny node.js debugging utility modelled after node core's debugging technique. + +**Discussion around the V3 API is under way [here](https://github.com/visionmedia/debug/issues/370)** + +## Installation + +```bash +$ npm install debug +``` + +## Usage + +`debug` exposes a function; simply pass this function the name of your module, and it will return a decorated version of `console.error` for you to pass debug statements to. This will allow you to toggle the debug output for different parts of your module as well as the module as a whole. + +Example _app.js_: + +```js +var debug = require('debug')('http') + , http = require('http') + , name = 'My App'; + +// fake app + +debug('booting %s', name); + +http.createServer(function(req, res){ + debug(req.method + ' ' + req.url); + res.end('hello\n'); +}).listen(3000, function(){ + debug('listening'); +}); + +// fake worker of some kind + +require('./worker'); +``` + +Example _worker.js_: + +```js +var debug = require('debug')('worker'); + +setInterval(function(){ + debug('doing some work'); +}, 1000); +``` + + The __DEBUG__ environment variable is then used to enable these based on space or comma-delimited names. Here are some examples: + +  + +  + +#### Windows note + + On Windows the environment variable is set using the `set` command. + + ```cmd + set DEBUG=*,-not_this + ``` + + Note that PowerShell uses different syntax to set environment variables. + + ```cmd + $env:DEBUG = "*,-not_this" + ``` + +Then, run the program to be debugged as usual. + +## Millisecond diff + + When actively developing an application it can be useful to see when the time spent between one `debug()` call and the next. Suppose for example you invoke `debug()` before requesting a resource, and after as well, the "+NNNms" will show you how much time was spent between calls. + +  + + When stdout is not a TTY, `Date#toUTCString()` is used, making it more useful for logging the debug information as shown below: + +  + +## Conventions + + If you're using this in one or more of your libraries, you _should_ use the name of your library so that developers may toggle debugging as desired without guessing names. If you have more than one debuggers you _should_ prefix them with your library name and use ":" to separate features. For example "bodyParser" from Connect would then be "connect:bodyParser". + +## Wildcards + + The `*` character may be used as a wildcard. Suppose for example your library has debuggers named "connect:bodyParser", "connect:compress", "connect:session", instead of listing all three with `DEBUG=connect:bodyParser,connect:compress,connect:session`, you may simply do `DEBUG=connect:*`, or to run everything using this module simply use `DEBUG=*`. + + You can also exclude specific debuggers by prefixing them with a "-" character. For example, `DEBUG=*,-connect:*` would include all debuggers except those starting with "connect:". + +## Environment Variables + + When running through Node.js, you can set a few environment variables that will + change the behavior of the debug logging: + +| Name | Purpose | +|-----------|-------------------------------------------------| +| `DEBUG` | Enables/disables specific debugging namespaces. | +| `DEBUG_COLORS`| Whether or not to use colors in the debug output. | +| `DEBUG_DEPTH` | Object inspection depth. | +| `DEBUG_SHOW_HIDDEN` | Shows hidden properties on inspected objects. | + + + __Note:__ The environment variables beginning with `DEBUG_` end up being + converted into an Options object that gets used with `%o`/`%O` formatters. + See the Node.js documentation for + [`util.inspect()`](https://nodejs.org/api/util.html#util_util_inspect_object_options) + for the complete list. + +## Formatters + + + Debug uses [printf-style](https://wikipedia.org/wiki/Printf_format_string) formatting. Below are the officially supported formatters: + +| Formatter | Representation | +|-----------|----------------| +| `%O` | Pretty-print an Object on multiple lines. | +| `%o` | Pretty-print an Object all on a single line. | +| `%s` | String. | +| `%d` | Number (both integer and float). | +| `%j` | JSON. Replaced with the string '[Circular]' if the argument contains circular references. | +| `%%` | Single percent sign ('%'). This does not consume an argument. | + +### Custom formatters + + You can add custom formatters by extending the `debug.formatters` object. For example, if you wanted to add support for rendering a Buffer as hex with `%h`, you could do something like: + +```js +const createDebug = require('debug') +createDebug.formatters.h = (v) => { + return v.toString('hex') +} + +// …elsewhere +const debug = createDebug('foo') +debug('this is hex: %h', new Buffer('hello world')) +// foo this is hex: 68656c6c6f20776f726c6421 +0ms +``` + +## Browser support + You can build a browser-ready script using [browserify](https://github.com/substack/node-browserify), + or just use the [browserify-as-a-service](https://wzrd.in/) [build](https://wzrd.in/standalone/debug@latest), + if you don't want to build it yourself. + + Debug's enable state is currently persisted by `localStorage`. + Consider the situation shown below where you have `worker:a` and `worker:b`, + and wish to debug both. You can enable this using `localStorage.debug`: + +```js +localStorage.debug = 'worker:*' +``` + +And then refresh the page. + +```js +a = debug('worker:a'); +b = debug('worker:b'); + +setInterval(function(){ + a('doing some work'); +}, 1000); + +setInterval(function(){ + b('doing some work'); +}, 1200); +``` + +#### Web Inspector Colors + + Colors are also enabled on "Web Inspectors" that understand the `%c` formatting + option. These are WebKit web inspectors, Firefox ([since version + 31](https://hacks.mozilla.org/2014/05/editable-box-model-multiple-selection-sublime-text-keys-much-more-firefox-developer-tools-episode-31/)) + and the Firebug plugin for Firefox (any version). + + Colored output looks something like: + +  + + +## Output streams + + By default `debug` will log to stderr, however this can be configured per-namespace by overriding the `log` method: + +Example _stdout.js_: + +```js +var debug = require('debug'); +var error = debug('app:error'); + +// by default stderr is used +error('goes to stderr!'); + +var log = debug('app:log'); +// set this namespace to log via console.log +log.log = console.log.bind(console); // don't forget to bind to console! +log('goes to stdout'); +error('still goes to stderr!'); + +// set all output to go via console.info +// overrides all per-namespace log settings +debug.log = console.info.bind(console); +error('now goes to stdout via console.info'); +log('still goes to stdout, but via console.info now'); +``` + + +## Authors + + - TJ Holowaychuk + - Nathan Rajlich + - Andrew Rhyne + +## Backers + +Support us with a monthly donation and help us continue our activities. [[Become a backer](https://opencollective.com/debug#backer)] + +<a href="https://opencollective.com/debug/backer/0/website" target="_blank"><img src="https://opencollective.com/debug/backer/0/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/1/website" target="_blank"><img src="https://opencollective.com/debug/backer/1/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/2/website" target="_blank"><img src="https://opencollective.com/debug/backer/2/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/3/website" target="_blank"><img src="https://opencollective.com/debug/backer/3/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/4/website" target="_blank"><img src="https://opencollective.com/debug/backer/4/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/5/website" target="_blank"><img src="https://opencollective.com/debug/backer/5/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/6/website" target="_blank"><img src="https://opencollective.com/debug/backer/6/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/7/website" target="_blank"><img src="https://opencollective.com/debug/backer/7/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/8/website" target="_blank"><img src="https://opencollective.com/debug/backer/8/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/9/website" target="_blank"><img src="https://opencollective.com/debug/backer/9/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/10/website" target="_blank"><img src="https://opencollective.com/debug/backer/10/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/11/website" target="_blank"><img src="https://opencollective.com/debug/backer/11/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/12/website" target="_blank"><img src="https://opencollective.com/debug/backer/12/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/13/website" target="_blank"><img src="https://opencollective.com/debug/backer/13/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/14/website" target="_blank"><img src="https://opencollective.com/debug/backer/14/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/15/website" target="_blank"><img src="https://opencollective.com/debug/backer/15/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/16/website" target="_blank"><img src="https://opencollective.com/debug/backer/16/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/17/website" target="_blank"><img src="https://opencollective.com/debug/backer/17/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/18/website" target="_blank"><img src="https://opencollective.com/debug/backer/18/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/19/website" target="_blank"><img src="https://opencollective.com/debug/backer/19/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/20/website" target="_blank"><img src="https://opencollective.com/debug/backer/20/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/21/website" target="_blank"><img src="https://opencollective.com/debug/backer/21/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/22/website" target="_blank"><img src="https://opencollective.com/debug/backer/22/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/23/website" target="_blank"><img src="https://opencollective.com/debug/backer/23/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/24/website" target="_blank"><img src="https://opencollective.com/debug/backer/24/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/25/website" target="_blank"><img src="https://opencollective.com/debug/backer/25/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/26/website" target="_blank"><img src="https://opencollective.com/debug/backer/26/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/27/website" target="_blank"><img src="https://opencollective.com/debug/backer/27/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/28/website" target="_blank"><img src="https://opencollective.com/debug/backer/28/avatar.svg"></a> +<a href="https://opencollective.com/debug/backer/29/website" target="_blank"><img src="https://opencollective.com/debug/backer/29/avatar.svg"></a> + + +## Sponsors + +Become a sponsor and get your logo on our README on Github with a link to your site. [[Become a sponsor](https://opencollective.com/debug#sponsor)] + +<a href="https://opencollective.com/debug/sponsor/0/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/0/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/1/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/1/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/2/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/2/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/3/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/3/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/4/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/4/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/5/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/5/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/6/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/6/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/7/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/7/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/8/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/8/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/9/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/9/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/10/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/10/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/11/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/11/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/12/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/12/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/13/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/13/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/14/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/14/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/15/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/15/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/16/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/16/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/17/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/17/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/18/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/18/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/19/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/19/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/20/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/20/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/21/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/21/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/22/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/22/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/23/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/23/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/24/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/24/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/25/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/25/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/26/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/26/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/27/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/27/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/28/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/28/avatar.svg"></a> +<a href="https://opencollective.com/debug/sponsor/29/website" target="_blank"><img src="https://opencollective.com/debug/sponsor/29/avatar.svg"></a> + +## License + +(The MIT License) + +Copyright (c) 2014-2016 TJ Holowaychuk <tj@vision-media.ca> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/component.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/component.json new file mode 100644 index 0000000000000000000000000000000000000000..9de26410f0d0bba2e48a07f094407d602eb5dd89 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/component.json @@ -0,0 +1,19 @@ +{ + "name": "debug", + "repo": "visionmedia/debug", + "description": "small debugging utility", + "version": "2.6.9", + "keywords": [ + "debug", + "log", + "debugger" + ], + "main": "src/browser.js", + "scripts": [ + "src/browser.js", + "src/debug.js" + ], + "dependencies": { + "rauchg/ms.js": "0.7.1" + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/karma.conf.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/karma.conf.js new file mode 100644 index 0000000000000000000000000000000000000000..103a82d15bd72b3cdf9ba4108272985f7e0bfdb3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/karma.conf.js @@ -0,0 +1,70 @@ +// Karma configuration +// Generated on Fri Dec 16 2016 13:09:51 GMT+0000 (UTC) + +module.exports = function(config) { + config.set({ + + // base path that will be used to resolve all patterns (eg. files, exclude) + basePath: '', + + + // frameworks to use + // available frameworks: https://npmjs.org/browse/keyword/karma-adapter + frameworks: ['mocha', 'chai', 'sinon'], + + + // list of files / patterns to load in the browser + files: [ + 'dist/debug.js', + 'test/*spec.js' + ], + + + // list of files to exclude + exclude: [ + 'src/node.js' + ], + + + // preprocess matching files before serving them to the browser + // available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor + preprocessors: { + }, + + // test results reporter to use + // possible values: 'dots', 'progress' + // available reporters: https://npmjs.org/browse/keyword/karma-reporter + reporters: ['progress'], + + + // web server port + port: 9876, + + + // enable / disable colors in the output (reporters and logs) + colors: true, + + + // level of logging + // possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG + logLevel: config.LOG_INFO, + + + // enable / disable watching file and executing tests whenever any file changes + autoWatch: true, + + + // start these browsers + // available browser launchers: https://npmjs.org/browse/keyword/karma-launcher + browsers: ['PhantomJS'], + + + // Continuous Integration mode + // if true, Karma captures browsers, runs the tests and exits + singleRun: false, + + // Concurrency level + // how many browser should be started simultaneous + concurrency: Infinity + }) +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/node.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/node.js new file mode 100644 index 0000000000000000000000000000000000000000..7fc36fe6dbecbfd41530c5a490cc738ec2968653 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/node.js @@ -0,0 +1 @@ +module.exports = require('./src/node'); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/package.json new file mode 100644 index 0000000000000000000000000000000000000000..e06c2429b209e2cccd09bfc43bdfbf66832e3580 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/package.json @@ -0,0 +1,88 @@ +{ + "_from": "debug@^2.2.0", + "_id": "debug@2.6.9", + "_inBundle": false, + "_integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "_location": "/debug", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "debug@^2.2.0", + "name": "debug", + "escapedName": "debug", + "rawSpec": "^2.2.0", + "saveSpec": null, + "fetchSpec": "^2.2.0" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "_shasum": "5d128515df134ff327e90a4c93f4e077a536341f", + "_spec": "debug@^2.2.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "TJ Holowaychuk", + "email": "tj@vision-media.ca" + }, + "browser": "./src/browser.js", + "bugs": { + "url": "https://github.com/visionmedia/debug/issues" + }, + "bundleDependencies": false, + "component": { + "scripts": { + "debug/index.js": "browser.js", + "debug/debug.js": "debug.js" + } + }, + "contributors": [ + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "http://n8.io" + }, + { + "name": "Andrew Rhyne", + "email": "rhyneandrew@gmail.com" + } + ], + "dependencies": { + "ms": "2.0.0" + }, + "deprecated": false, + "description": "small debugging utility", + "devDependencies": { + "browserify": "9.0.3", + "chai": "^3.5.0", + "concurrently": "^3.1.0", + "coveralls": "^2.11.15", + "eslint": "^3.12.1", + "istanbul": "^0.4.5", + "karma": "^1.3.0", + "karma-chai": "^0.1.0", + "karma-mocha": "^1.3.0", + "karma-phantomjs-launcher": "^1.0.2", + "karma-sinon": "^1.0.5", + "mocha": "^3.2.0", + "mocha-lcov-reporter": "^1.2.0", + "rimraf": "^2.5.4", + "sinon": "^1.17.6", + "sinon-chai": "^2.8.0" + }, + "homepage": "https://github.com/visionmedia/debug#readme", + "keywords": [ + "debug", + "log", + "debugger" + ], + "license": "MIT", + "main": "./src/index.js", + "name": "debug", + "repository": { + "type": "git", + "url": "git://github.com/visionmedia/debug.git" + }, + "version": "2.6.9" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..7106924934501fd4035efe78678281020328acc5 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/browser.js @@ -0,0 +1,185 @@ +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); + +/** + * Colors. + */ + +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; + + +/** + * Colorize log arguments if enabled. + * + * @api public + */ + +function formatArgs(args) { + var useColors = this.useColors; + + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); + + if (!useColors) return; + + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') + + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); +} + +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ + +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } + + return r; +} + +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/debug.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/debug.js new file mode 100644 index 0000000000000000000000000000000000000000..6a5e3fc94c3ab80e123c3056b6c5dbe056d21658 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/debug.js @@ -0,0 +1,202 @@ + +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = require('ms'); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/index.js new file mode 100644 index 0000000000000000000000000000000000000000..e12cf4d58c9f2d6d2d2e656f9cbb0f703cb5fa29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/index.js @@ -0,0 +1,10 @@ +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = require('./browser.js'); +} else { + module.exports = require('./node.js'); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/inspector-log.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/inspector-log.js new file mode 100644 index 0000000000000000000000000000000000000000..60ea6c04aafd41d0ea3bcd78f58312ecf0eda436 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/inspector-log.js @@ -0,0 +1,15 @@ +module.exports = inspectorLog; + +// black hole +const nullStream = new (require('stream').Writable)(); +nullStream._write = () => {}; + +/** + * Outputs a `console.log()` to the Node.js Inspector console *only*. + */ +function inspectorLog() { + const stdout = console._stdout; + console._stdout = nullStream; + console.log.apply(console, arguments); + console._stdout = stdout; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/node.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/node.js new file mode 100644 index 0000000000000000000000000000000000000000..b15109c905a45bcb5db701cf37cf4e19385c3167 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/debug/src/node.js @@ -0,0 +1,248 @@ +/** + * Module dependencies. + */ + +var tty = require('tty'); +var util = require('util'); + +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ + +exports = module.exports = require('./debug'); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; + +/** + * Colors. + */ + +exports.colors = [6, 2, 3, 4, 5, 1]; + +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ + +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = require('fs'); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = require('net'); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ + +function init (debug) { + debug.inspectOpts = {}; + + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} + +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ + +exports.enable(load()); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/LICENSE.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..ee27ba4b4412b0e4a05af5e3d8a005bc6681fdf3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/LICENSE.md @@ -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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/README.md new file mode 100644 index 0000000000000000000000000000000000000000..275286391935842285d869d8a18949e04ca20fdf --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/README.md @@ -0,0 +1,16 @@ +# is-typedarray [](http://github.com/badges/stability-badges) + +Detect whether or not an object is a +[Typed Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Typed_arrays). + +## Usage + +[](https://nodei.co/npm/is-typedarray/) + +### isTypedArray(array) + +Returns `true` when array is a Typed Array, and `false` when it is not. + +## License + +MIT. See [LICENSE.md](http://github.com/hughsk/is-typedarray/blob/master/LICENSE.md) for details. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/index.js new file mode 100644 index 0000000000000000000000000000000000000000..58596036cdf15908a729e6547936eef72b2d2e60 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/index.js @@ -0,0 +1,41 @@ +module.exports = isTypedArray +isTypedArray.strict = isStrictTypedArray +isTypedArray.loose = isLooseTypedArray + +var toString = Object.prototype.toString +var names = { + '[object Int8Array]': true + , '[object Int16Array]': true + , '[object Int32Array]': true + , '[object Uint8Array]': true + , '[object Uint8ClampedArray]': true + , '[object Uint16Array]': true + , '[object Uint32Array]': true + , '[object Float32Array]': true + , '[object Float64Array]': true +} + +function isTypedArray(arr) { + return ( + isStrictTypedArray(arr) + || isLooseTypedArray(arr) + ) +} + +function isStrictTypedArray(arr) { + return ( + arr instanceof Int8Array + || arr instanceof Int16Array + || arr instanceof Int32Array + || arr instanceof Uint8Array + || arr instanceof Uint8ClampedArray + || arr instanceof Uint16Array + || arr instanceof Uint32Array + || arr instanceof Float32Array + || arr instanceof Float64Array + ) +} + +function isLooseTypedArray(arr) { + return names[toString.call(arr)] +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d3638d95265bfd714cb0ca7f61bbbf5b567565ba --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/package.json @@ -0,0 +1,59 @@ +{ + "_from": "is-typedarray@^1.0.0", + "_id": "is-typedarray@1.0.0", + "_inBundle": false, + "_integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=", + "_location": "/is-typedarray", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "is-typedarray@^1.0.0", + "name": "is-typedarray", + "escapedName": "is-typedarray", + "rawSpec": "^1.0.0", + "saveSpec": null, + "fetchSpec": "^1.0.0" + }, + "_requiredBy": [ + "/typedarray-to-buffer" + ], + "_resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "_shasum": "e479c80858df0c1b11ddda6940f96011fcda4a9a", + "_spec": "is-typedarray@^1.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/typedarray-to-buffer", + "author": { + "name": "Hugh Kennedy", + "email": "hughskennedy@gmail.com", + "url": "http://hughsk.io/" + }, + "bugs": { + "url": "https://github.com/hughsk/is-typedarray/issues" + }, + "bundleDependencies": false, + "dependencies": {}, + "deprecated": false, + "description": "Detect whether or not an object is a Typed Array", + "devDependencies": { + "tape": "^2.13.1" + }, + "homepage": "https://github.com/hughsk/is-typedarray", + "keywords": [ + "typed", + "array", + "detect", + "is", + "util" + ], + "license": "MIT", + "main": "index.js", + "name": "is-typedarray", + "repository": { + "type": "git", + "url": "git://github.com/hughsk/is-typedarray.git" + }, + "scripts": { + "test": "node test" + }, + "version": "1.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/test.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/test.js new file mode 100644 index 0000000000000000000000000000000000000000..b0c176fa302aa0c3aacab1287893ee5c1f8b07d6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/is-typedarray/test.js @@ -0,0 +1,34 @@ +var test = require('tape') +var ista = require('./') + +test('strict', function(t) { + t.ok(ista.strict(new Int8Array), 'Int8Array') + t.ok(ista.strict(new Int16Array), 'Int16Array') + t.ok(ista.strict(new Int32Array), 'Int32Array') + t.ok(ista.strict(new Uint8Array), 'Uint8Array') + t.ok(ista.strict(new Uint16Array), 'Uint16Array') + t.ok(ista.strict(new Uint32Array), 'Uint32Array') + t.ok(ista.strict(new Float32Array), 'Float32Array') + t.ok(ista.strict(new Float64Array), 'Float64Array') + + t.ok(!ista.strict(new Array), 'Array') + t.ok(!ista.strict([]), '[]') + + t.end() +}) + +test('loose', function(t) { + t.ok(ista.loose(new Int8Array), 'Int8Array') + t.ok(ista.loose(new Int16Array), 'Int16Array') + t.ok(ista.loose(new Int32Array), 'Int32Array') + t.ok(ista.loose(new Uint8Array), 'Uint8Array') + t.ok(ista.loose(new Uint16Array), 'Uint16Array') + t.ok(ista.loose(new Uint32Array), 'Uint32Array') + t.ok(ista.loose(new Float32Array), 'Float32Array') + t.ok(ista.loose(new Float64Array), 'Float64Array') + + t.ok(!ista.loose(new Array), 'Array') + t.ok(!ista.loose([]), '[]') + + t.end() +}) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6a522b16b3a3bf5e93aa5b8bf485f866ff71c5c2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/index.js @@ -0,0 +1,152 @@ +/** + * Helpers. + */ + +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; + +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ + +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; + +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ + +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} + +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} + +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ + +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} + +/** + * Pluralization helper. + */ + +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/license.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/license.md new file mode 100644 index 0000000000000000000000000000000000000000..69b61253a38926757b7de1d4df4880fc2105c2c9 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/license.md @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2016 Zeit, Inc. + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/package.json new file mode 100644 index 0000000000000000000000000000000000000000..a4e0bc23516ba7d553444e45f90693e05e88916f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/package.json @@ -0,0 +1,69 @@ +{ + "_from": "ms@2.0.0", + "_id": "ms@2.0.0", + "_inBundle": false, + "_integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=", + "_location": "/ms", + "_phantomChildren": {}, + "_requested": { + "type": "version", + "registry": true, + "raw": "ms@2.0.0", + "name": "ms", + "escapedName": "ms", + "rawSpec": "2.0.0", + "saveSpec": null, + "fetchSpec": "2.0.0" + }, + "_requiredBy": [ + "/debug" + ], + "_resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "_shasum": "5608aeadfc00be6c2901df5f9861788de0d597c8", + "_spec": "ms@2.0.0", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/debug", + "bugs": { + "url": "https://github.com/zeit/ms/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Tiny milisecond conversion utility", + "devDependencies": { + "eslint": "3.19.0", + "expect.js": "0.3.1", + "husky": "0.13.3", + "lint-staged": "3.4.1", + "mocha": "3.4.1" + }, + "eslintConfig": { + "extends": "eslint:recommended", + "env": { + "node": true, + "es6": true + } + }, + "files": [ + "index.js" + ], + "homepage": "https://github.com/zeit/ms#readme", + "license": "MIT", + "lint-staged": { + "*.js": [ + "npm run lint", + "prettier --single-quote --write", + "git add" + ] + }, + "main": "./index", + "name": "ms", + "repository": { + "type": "git", + "url": "git+https://github.com/zeit/ms.git" + }, + "scripts": { + "lint": "eslint lib/* bin/*", + "precommit": "lint-staged", + "test": "mocha tests.js" + }, + "version": "2.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/readme.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/readme.md new file mode 100644 index 0000000000000000000000000000000000000000..84a9974cccd81f9296b7d3c77f2b0d2765dfe181 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ms/readme.md @@ -0,0 +1,51 @@ +# ms + +[](https://travis-ci.org/zeit/ms) +[](https://zeit.chat/) + +Use this package to easily convert various time formats to milliseconds. + +## Examples + +```js +ms('2 days') // 172800000 +ms('1d') // 86400000 +ms('10h') // 36000000 +ms('2.5 hrs') // 9000000 +ms('2h') // 7200000 +ms('1m') // 60000 +ms('5s') // 5000 +ms('1y') // 31557600000 +ms('100') // 100 +``` + +### Convert from milliseconds + +```js +ms(60000) // "1m" +ms(2 * 60000) // "2m" +ms(ms('10 hours')) // "10h" +``` + +### Time format written-out + +```js +ms(60000, { long: true }) // "1 minute" +ms(2 * 60000, { long: true }) // "2 minutes" +ms(ms('10 hours'), { long: true }) // "10 hours" +``` + +## Features + +- Works both in [node](https://nodejs.org) and in the browser. +- If a number is supplied to `ms`, a string with a unit is returned. +- If a string that contains the number is supplied, it returns it as a number (e.g.: it returns `100` for `'100'`). +- If you pass a string with a number and a valid unit, the number of equivalent ms is returned. + +## Caught a bug? + +1. [Fork](https://help.github.com/articles/fork-a-repo/) this repository to your own GitHub account and then [clone](https://help.github.com/articles/cloning-a-repository/) it to your local device +2. Link the package to the global module directory: `npm link` +3. Within the module you want to test your local development instance of ms, just link it to the dependencies: `npm link ms`. Instead of the default one from npm, node will now use your clone of ms! + +As always, you can run the tests using: `npm test` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..091cdd1cc9a3c83d66ce6aac072e21a684b72613 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/CHANGELOG.md @@ -0,0 +1,492 @@ +# NAN ChangeLog + +**Version 2.10.0: current Node 9.8.0, Node 0.12: 0.12.18, Node 0.10: 0.10.48, iojs: 3.3.1** + +### 2.10.0 Mar 16 2018 + + - Deprecation: Deprecate `MakeCallback` 5e92b19a59e194241d6a658bd6ff7bfbda372950 + - Feature: add `Nan::Call` overload 4482e1242fe124d166fc1a5b2be3c1cc849fe452 + - Feature: add more `Nan::Call` overloads 8584e63e6d04c7d2eb8c4a664e4ef57d70bf672b + - Feature: Fix deprecation warnings for Node 10 1caf258243b0602ed56922bde74f1c91b0cbcb6a + +### 2.9.2 Feb 22 2018 + + - Bugfix: Bandaid for async hooks 212bd2f849be14ef1b02fc85010b053daa24252b + +### 2.9.1 Feb 22 2018 + + - Bugfix: Avoid deprecation warnings in deprecated `Nan::Callback::operator()` 372b14d91289df4604b0f81780709708c45a9aa4 + - Bugfix: Avoid deprecation warnings in `Nan::JSON` 3bc294bce0b7d0a3ee4559926303e5ed4866fda2 + +### 2.9.0 Feb 22 2018 + + - Deprecation: Deprecate legacy `Callback::Call` 6dd5fa690af61ca3523004b433304c581b3ea309 + - Feature: introduce `AsyncResource` class 90c0a179c0d8cb5fd26f1a7d2b1d6231eb402d48o + - Feature: Add context aware `Nan::Callback::Call` functions 7169e09fb088418b6e388222e88b4c13f07ebaee + - Feature: Make `AsyncWorker` context aware 066ba21a6fb9e2b5230c9ed3a6fc51f1211736a4 + - Feature: add `Callback` overload to `Nan::Call` 5328daf66e202658c1dc0d916c3aaba99b3cc606 + - Bugfix: fix warning: suggest parentheses around `&&` within `||` b2bb63d68b8ae623a526b542764e1ac82319cb2c + - Bugfix: Fix compilation on io.js 3 d06114dba0a522fb436f0c5f47b994210968cd7b + +### 2.8.0 Nov 15 2017 + + - Deprecation: Deprecate `Nan::ForceSet` in favor of `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + - Feature: Add `Nan::AsyncProgressQueueWorker` a976636ecc2ef617d1b061ce4a6edf39923691cb + - Feature: Add `Nan::DefineOwnProperty()` 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + - Bugfix: Fix compiling on io.js 1 & 2 82705a64503ce60c62e98df5bd02972bba090900 + - Bugfix: Use DefineOwnProperty instead of ForceSet 95cbb976d6fbbba88ba0f86dd188223a8591b4e7 + +### 2.7.0 Aug 30 2017 + + - Feature: Add `Nan::To<v8::Function>()` overload. b93280670c9f6da42ed4cf6cbf085ffdd87bd65b + - Bugfix: Fix ternary in `Nan::MaybeLocal<T>::FromMaybe<S>()`. 79a26f7d362e756a9524e672a82c3d603b542867 + +### 2.6.2 Apr 12 2017 + + - Bugfix: Fix v8::JSON::Parse() deprecation warning. 87f6a3c65815fa062296a994cc863e2fa124867d + +### 2.6.1 Apr 6 2017 + + - Bugfix: nan_json.h: fix build breakage in Node 6 ac8d47dc3c10bfbf3f15a6b951633120c0ee6d51 + +### 2.6.0 Apr 6 2017 + + - Feature: nan: add support for JSON::Parse & Stringify b533226c629cce70e1932a873bb6f849044a56c5 + +### 2.5.1 Jan 23 2017 + + - Bugfix: Fix disappearing handle for private value 6a80995694f162ef63dbc9948fbefd45d4485aa0 + - Bugfix: Add missing scopes a93b8bae6bc7d32a170db6e89228b7f60ee57112 + - Bugfix: Use string::data instead of string::front in NewOneByteString d5f920371e67e1f3b268295daee6e83af86b6e50 + +### 2.5.0 Dec 21 2016 + + - Feature: Support Private accessors a86255cb357e8ad8ccbf1f6a4a901c921e39a178 + - Bugfix: Abort in delete operators that shouldn't be called 0fe38215ff8581703967dfd26c12793feb960018 + +### 2.4.0 Jul 10 2016 + + - Feature: Rewrite Callback to add Callback::Reset c4cf44d61f8275cd5f7b0c911d7a806d4004f649 + - Feature: AsyncProgressWorker: add template types for .send 1242c9a11a7ed481c8f08ec06316385cacc513d0 + - Bugfix: Add constness to old Persistent comparison operators bd43cb9982c7639605d60fd073efe8cae165d9b2 + +### 2.3.5 May 31 2016 + + - Bugfix: Replace NAN_INLINE with 'inline' keyword. 71819d8725f822990f439479c9aba3b240804909 + +### 2.3.4 May 31 2016 + + - Bugfix: Remove V8 deprecation warnings 0592fb0a47f3a1c7763087ebea8e1138829f24f9 + - Bugfix: Fix new versions not to use WeakCallbackInfo::IsFirstPass 615c19d9e03d4be2049c10db0151edbc3b229246 + - Bugfix: Make ObjectWrap::handle() const d19af99595587fe7a26bd850af6595c2a7145afc + - Bugfix: Fix compilation errors related to 0592fb0a47f3a1c7763087ebea8e1138829f24f9 e9191c525b94f652718325e28610a1adcf90fed8 + +### 2.3.3 May 4 2016 + + - Bugfix: Refactor SetMethod() to deal with v8::Templates (#566) b9083cf6d5de6ebe6bcb49c7502fbb7c0d9ddda8 + +### 2.3.2 Apr 27 2016 + + - Bugfix: Fix compilation on outdated versions due to Handle removal f8b7c875d04d425a41dfd4f3f8345bc3a11e6c52 + +### 2.3.1 Apr 27 2016 + + - Bugfix: Don't use deprecated v8::Template::Set() in SetMethod a90951e9ea70fa1b3836af4b925322919159100e + +### 2.3.0 Apr 27 2016 + + - Feature: added Signal() for invoking async callbacks without sending data from AsyncProgressWorker d8adba45f20e077d00561b20199133620c990b38 + - Bugfix: Don't use deprecated v8::Template::Set() 00dacf0a4b86027415867fa7f1059acc499dcece + +### 2.2.1 Mar 29 2016 + + - Bugfix: Use NewFromUnsigned in ReturnValue<T>::Set(uint32_t i) for pre_12 3a18f9bdce29826e0e4c217854bc476918241a58 + - Performance: Remove unneeeded nullptr checks b715ef44887931c94f0d1605b3b1a4156eebece9 + +### 2.2.0 Jan 9 2016 + + - Feature: Add Function::Call wrapper 4c157474dacf284d125c324177b45aa5dabc08c6 + - Feature: Rename GC*logueCallback to GCCallback for > 4.0 3603435109f981606d300eb88004ca101283acec + - Bugfix: Fix Global::Pass for old versions 367e82a60fbaa52716232cc89db1cc3f685d77d9 + - Bugfix: Remove weird MaybeLocal wrapping of what already is a MaybeLocal 23b4590db10c2ba66aee2338aebe9751c4cb190b + +### 2.1.0 Oct 8 2015 + + - Deprecation: Deprecate NanErrnoException in favor of ErrnoException 0af1ca4cf8b3f0f65ed31bc63a663ab3319da55c + - Feature: added helper class for accessing contents of typedarrays 17b51294c801e534479d5463697a73462d0ca555 + - Feature: [Maybe types] Add MakeMaybe(...) 48d7b53d9702b0c7a060e69ea10fea8fb48d814d + - Feature: new: allow utf16 string with length 66ac6e65c8ab9394ef588adfc59131b3b9d8347b + - Feature: Introduce SetCallHandler and SetCallAsFunctionHandler 7764a9a115d60ba10dc24d86feb0fbc9b4f75537 + - Bugfix: Enable creating Locals from Globals under Node 0.10. 9bf9b8b190821af889790fdc18ace57257e4f9ff + - Bugfix: Fix issue #462 where PropertyCallbackInfo data is not stored safely. 55f50adedd543098526c7b9f4fffd607d3f9861f + +### 2.0.9 Sep 8 2015 + + - Bugfix: EscapableHandleScope in Nan::NewBuffer for Node 0.8 and 0.10 b1654d7 + +### 2.0.8 Aug 28 2015 + + - Work around duplicate linking bug in clang 11902da + +### 2.0.7 Aug 26 2015 + + - Build: Repackage + +### 2.0.6 Aug 26 2015 + + - Bugfix: Properly handle null callback in FunctionTemplate factory 6e99cb1 + - Bugfix: Remove unused static std::map instances 525bddc + - Bugfix: Make better use of maybe versions of APIs bfba85b + - Bugfix: Fix shadowing issues with handle in ObjectWrap 0a9072d + +### 2.0.5 Aug 10 2015 + + - Bugfix: Reimplement weak callback in ObjectWrap 98d38c1 + - Bugfix: Make sure callback classes are not assignable, copyable or movable 81f9b1d + +### 2.0.4 Aug 6 2015 + + - Build: Repackage + +### 2.0.3 Aug 6 2015 + + - Bugfix: Don't use clang++ / g++ syntax extension. 231450e + +### 2.0.2 Aug 6 2015 + + - Build: Repackage + +### 2.0.1 Aug 6 2015 + + - Bugfix: Add workaround for missing REPLACE_INVALID_UTF8 60d6687 + - Bugfix: Reimplement ObjectWrap from scratch to prevent memory leaks 6484601 + - Bugfix: Fix Persistent leak in FunctionCallbackInfo and PropertyCallbackInfo 641ef5f + - Bugfix: Add missing overload for Nan::NewInstance that takes argc/argv 29450ed + +### 2.0.0 Jul 31 2015 + + - Change: Renamed identifiers with leading underscores b5932b4 + - Change: Replaced NanObjectWrapHandle with class NanObjectWrap 464f1e1 + - Change: Replace NanScope and NanEscpableScope macros with classes 47751c4 + - Change: Rename NanNewBufferHandle to NanNewBuffer 6745f99 + - Change: Rename NanBufferUse to NanNewBuffer 3e8b0a5 + - Change: Rename NanNewBuffer to NanCopyBuffer d6af78d + - Change: Remove Nan prefix from all names 72d1f67 + - Change: Update Buffer API for new upstream changes d5d3291 + - Change: Rename Scope and EscapableScope to HandleScope and EscapableHandleScope 21a7a6a + - Change: Get rid of Handles e6c0daf + - Feature: Support io.js 3 with V8 4.4 + - Feature: Introduce NanPersistent 7fed696 + - Feature: Introduce NanGlobal 4408da1 + - Feature: Added NanTryCatch 10f1ca4 + - Feature: Update for V8 v4.3 4b6404a + - Feature: Introduce NanNewOneByteString c543d32 + - Feature: Introduce namespace Nan 67ed1b1 + - Removal: Remove NanLocker and NanUnlocker dd6e401 + - Removal: Remove string converters, except NanUtf8String, which now follows the node implementation b5d00a9 + - Removal: Remove NanReturn* macros d90a25c + - Removal: Remove HasInstance e8f84fe + + +### 1.9.0 Jul 31 2015 + + - Feature: Added `NanFatalException` 81d4a2c + - Feature: Added more error types 4265f06 + - Feature: Added dereference and function call operators to NanCallback c4b2ed0 + - Feature: Added indexed GetFromPersistent and SaveToPersistent edd510c + - Feature: Added more overloads of SaveToPersistent and GetFromPersistent 8b1cef6 + - Feature: Added NanErrnoException dd87d9e + - Correctness: Prevent assign, copy, and move for classes that do not support it 1f55c59, 4b808cb, c96d9b2, fba4a29, 3357130 + - Deprecation: Deprecate `NanGetPointerSafe` and `NanSetPointerSafe` 81d4a2c + - Deprecation: Deprecate `NanBooleanOptionValue` and `NanUInt32OptionValue` 0ad254b + +### 1.8.4 Apr 26 2015 + + - Build: Repackage + +### 1.8.3 Apr 26 2015 + + - Bugfix: Include missing header 1af8648 + +### 1.8.2 Apr 23 2015 + + - Build: Repackage + +### 1.8.1 Apr 23 2015 + + - Bugfix: NanObjectWrapHandle should take a pointer 155f1d3 + +### 1.8.0 Apr 23 2015 + + - Feature: Allow primitives with NanReturnValue 2e4475e + - Feature: Added comparison operators to NanCallback 55b075e + - Feature: Backport thread local storage 15bb7fa + - Removal: Remove support for signatures with arguments 8a2069d + - Correcteness: Replaced NanObjectWrapHandle macro with function 0bc6d59 + +### 1.7.0 Feb 28 2015 + + - Feature: Made NanCallback::Call accept optional target 8d54da7 + - Feature: Support atom-shell 0.21 0b7f1bb + +### 1.6.2 Feb 6 2015 + + - Bugfix: NanEncode: fix argument type for node::Encode on io.js 2be8639 + +### 1.6.1 Jan 23 2015 + + - Build: version bump + +### 1.5.3 Jan 23 2015 + + - Build: repackage + +### 1.6.0 Jan 23 2015 + + - Deprecated `NanNewContextHandle` in favor of `NanNew<Context>` 49259af + - Support utility functions moved in newer v8 versions (Node 0.11.15, io.js 1.0) a0aa179 + - Added `NanEncode`, `NanDecodeBytes` and `NanDecodeWrite` 75e6fb9 + +### 1.5.2 Jan 23 2015 + + - Bugfix: Fix non-inline definition build error with clang++ 21d96a1, 60fadd4 + - Bugfix: Readded missing String constructors 18d828f + - Bugfix: Add overload handling NanNew<FunctionTemplate>(..) 5ef813b + - Bugfix: Fix uv_work_cb versioning 997e4ae + - Bugfix: Add function factory and test 4eca89c + - Bugfix: Add object template factory and test cdcb951 + - Correctness: Lifted an io.js related typedef c9490be + - Correctness: Make explicit downcasts of String lengths 00074e6 + - Windows: Limit the scope of disabled warning C4530 83d7deb + +### 1.5.1 Jan 15 2015 + + - Build: version bump + +### 1.4.3 Jan 15 2015 + + - Build: version bump + +### 1.4.2 Jan 15 2015 + + - Feature: Support io.js 0dbc5e8 + +### 1.5.0 Jan 14 2015 + + - Feature: Support io.js b003843 + - Correctness: Improved NanNew internals 9cd4f6a + - Feature: Implement progress to NanAsyncWorker 8d6a160 + +### 1.4.1 Nov 8 2014 + + - Bugfix: Handle DEBUG definition correctly + - Bugfix: Accept int as Boolean + +### 1.4.0 Nov 1 2014 + + - Feature: Added NAN_GC_CALLBACK 6a5c245 + - Performance: Removed unnecessary local handle creation 18a7243, 41fe2f8 + - Correctness: Added constness to references in NanHasInstance 02c61cd + - Warnings: Fixed spurious warnings from -Wundef and -Wshadow, 541b122, 99d8cb6 + - Windoze: Shut Visual Studio up when compiling 8d558c1 + - License: Switch to plain MIT from custom hacked MIT license 11de983 + - Build: Added test target to Makefile e232e46 + - Performance: Removed superfluous scope in NanAsyncWorker f4b7821 + - Sugar/Feature: Added NanReturnThis() and NanReturnHolder() shorthands 237a5ff, d697208 + - Feature: Added suitable overload of NanNew for v8::Integer::NewFromUnsigned b27b450 + +### 1.3.0 Aug 2 2014 + + - Added NanNew<v8::String, std::string>(std::string) + - Added NanNew<v8::String, std::string&>(std::string&) + - Added NanAsciiString helper class + - Added NanUtf8String helper class + - Added NanUcs2String helper class + - Deprecated NanRawString() + - Deprecated NanCString() + - Added NanGetIsolateData(v8::Isolate *isolate) + - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::Function> func, int argc, v8::Handle<v8::Value>* argv) + - Added NanMakeCallback(v8::Handle<v8::Object> target, v8::Handle<v8::String> symbol, int argc, v8::Handle<v8::Value>* argv) + - Added NanMakeCallback(v8::Handle<v8::Object> target, const char* method, int argc, v8::Handle<v8::Value>* argv) + - Added NanSetTemplate(v8::Handle<v8::Template> templ, v8::Handle<v8::String> name , v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + - Added NanSetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, const char *name, v8::Handle<v8::Data> value) + - Added NanSetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, v8::Handle<v8::String> name, v8::Handle<v8::Data> value, v8::PropertyAttribute attributes) + +### 1.2.0 Jun 5 2014 + + - Add NanSetPrototypeTemplate + - Changed NAN_WEAK_CALLBACK internals, switched _NanWeakCallbackData to class, + introduced _NanWeakCallbackDispatcher + - Removed -Wno-unused-local-typedefs from test builds + - Made test builds Windows compatible ('Sleep()') + +### 1.1.2 May 28 2014 + + - Release to fix more stuff-ups in 1.1.1 + +### 1.1.1 May 28 2014 + + - Release to fix version mismatch in nan.h and lack of changelog entry for 1.1.0 + +### 1.1.0 May 25 2014 + + - Remove nan_isolate, use v8::Isolate::GetCurrent() internally instead + - Additional explicit overloads for NanNew(): (char*,int), (uint8_t*[,int]), + (uint16_t*[,int), double, int, unsigned int, bool, v8::String::ExternalStringResource*, + v8::String::ExternalAsciiStringResource* + - Deprecate NanSymbol() + - Added SetErrorMessage() and ErrorMessage() to NanAsyncWorker + +### 1.0.0 May 4 2014 + + - Heavy API changes for V8 3.25 / Node 0.11.13 + - Use cpplint.py + - Removed NanInitPersistent + - Removed NanPersistentToLocal + - Removed NanFromV8String + - Removed NanMakeWeak + - Removed NanNewLocal + - Removed NAN_WEAK_CALLBACK_OBJECT + - Removed NAN_WEAK_CALLBACK_DATA + - Introduce NanNew, replaces NanNewLocal, NanPersistentToLocal, adds many overloaded typed versions + - Introduce NanUndefined, NanNull, NanTrue and NanFalse + - Introduce NanEscapableScope and NanEscapeScope + - Introduce NanMakeWeakPersistent (requires a special callback to work on both old and new node) + - Introduce NanMakeCallback for node::MakeCallback + - Introduce NanSetTemplate + - Introduce NanGetCurrentContext + - Introduce NanCompileScript and NanRunScript + - Introduce NanAdjustExternalMemory + - Introduce NanAddGCEpilogueCallback, NanAddGCPrologueCallback, NanRemoveGCEpilogueCallback, NanRemoveGCPrologueCallback + - Introduce NanGetHeapStatistics + - Rename NanAsyncWorker#SavePersistent() to SaveToPersistent() + +### 0.8.0 Jan 9 2014 + + - NanDispose -> NanDisposePersistent, deprecate NanDispose + - Extract _NAN_*_RETURN_TYPE, pull up NAN_*() + +### 0.7.1 Jan 9 2014 + + - Fixes to work against debug builds of Node + - Safer NanPersistentToLocal (avoid reinterpret_cast) + - Speed up common NanRawString case by only extracting flattened string when necessary + +### 0.7.0 Dec 17 2013 + + - New no-arg form of NanCallback() constructor. + - NanCallback#Call takes Handle rather than Local + - Removed deprecated NanCallback#Run method, use NanCallback#Call instead + - Split off _NAN_*_ARGS_TYPE from _NAN_*_ARGS + - Restore (unofficial) Node 0.6 compatibility at NanCallback#Call() + - Introduce NanRawString() for char* (or appropriate void*) from v8::String + (replacement for NanFromV8String) + - Introduce NanCString() for null-terminated char* from v8::String + +### 0.6.0 Nov 21 2013 + + - Introduce NanNewLocal<T>(v8::Handle<T> value) for use in place of + v8::Local<T>::New(...) since v8 started requiring isolate in Node 0.11.9 + +### 0.5.2 Nov 16 2013 + + - Convert SavePersistent and GetFromPersistent in NanAsyncWorker from protected and public + +### 0.5.1 Nov 12 2013 + + - Use node::MakeCallback() instead of direct v8::Function::Call() + +### 0.5.0 Nov 11 2013 + + - Added @TooTallNate as collaborator + - New, much simpler, "include_dirs" for binding.gyp + - Added full range of NAN_INDEX_* macros to match NAN_PROPERTY_* macros + +### 0.4.4 Nov 2 2013 + + - Isolate argument from v8::Persistent::MakeWeak removed for 0.11.8+ + +### 0.4.3 Nov 2 2013 + + - Include node_object_wrap.h, removed from node.h for Node 0.11.8. + +### 0.4.2 Nov 2 2013 + + - Handle deprecation of v8::Persistent::Dispose(v8::Isolate* isolate)) for + Node 0.11.8 release. + +### 0.4.1 Sep 16 2013 + + - Added explicit `#include <uv.h>` as it was removed from node.h for v0.11.8 + +### 0.4.0 Sep 2 2013 + + - Added NAN_INLINE and NAN_DEPRECATED and made use of them + - Added NanError, NanTypeError and NanRangeError + - Cleaned up code + +### 0.3.2 Aug 30 2013 + + - Fix missing scope declaration in GetFromPersistent() and SaveToPersistent + in NanAsyncWorker + +### 0.3.1 Aug 20 2013 + + - fix "not all control paths return a value" compile warning on some platforms + +### 0.3.0 Aug 19 2013 + + - Made NAN work with NPM + - Lots of fixes to NanFromV8String, pulling in features from new Node core + - Changed node::encoding to Nan::Encoding in NanFromV8String to unify the API + - Added optional error number argument for NanThrowError() + - Added NanInitPersistent() + - Added NanReturnNull() and NanReturnEmptyString() + - Added NanLocker and NanUnlocker + - Added missing scopes + - Made sure to clear disposed Persistent handles + - Changed NanAsyncWorker to allocate error messages on the heap + - Changed NanThrowError(Local<Value>) to NanThrowError(Handle<Value>) + - Fixed leak in NanAsyncWorker when errmsg is used + +### 0.2.2 Aug 5 2013 + + - Fixed usage of undefined variable with node::BASE64 in NanFromV8String() + +### 0.2.1 Aug 5 2013 + + - Fixed 0.8 breakage, node::BUFFER encoding type not available in 0.8 for + NanFromV8String() + +### 0.2.0 Aug 5 2013 + + - Added NAN_PROPERTY_GETTER, NAN_PROPERTY_SETTER, NAN_PROPERTY_ENUMERATOR, + NAN_PROPERTY_DELETER, NAN_PROPERTY_QUERY + - Extracted _NAN_METHOD_ARGS, _NAN_GETTER_ARGS, _NAN_SETTER_ARGS, + _NAN_PROPERTY_GETTER_ARGS, _NAN_PROPERTY_SETTER_ARGS, + _NAN_PROPERTY_ENUMERATOR_ARGS, _NAN_PROPERTY_DELETER_ARGS, + _NAN_PROPERTY_QUERY_ARGS + - Added NanGetInternalFieldPointer, NanSetInternalFieldPointer + - Added NAN_WEAK_CALLBACK, NAN_WEAK_CALLBACK_OBJECT, + NAN_WEAK_CALLBACK_DATA, NanMakeWeak + - Renamed THROW_ERROR to _NAN_THROW_ERROR + - Added NanNewBufferHandle(char*, size_t, node::smalloc::FreeCallback, void*) + - Added NanBufferUse(char*, uint32_t) + - Added NanNewContextHandle(v8::ExtensionConfiguration*, + v8::Handle<v8::ObjectTemplate>, v8::Handle<v8::Value>) + - Fixed broken NanCallback#GetFunction() + - Added optional encoding and size arguments to NanFromV8String() + - Added NanGetPointerSafe() and NanSetPointerSafe() + - Added initial test suite (to be expanded) + - Allow NanUInt32OptionValue to convert any Number object + +### 0.1.0 Jul 21 2013 + + - Added `NAN_GETTER`, `NAN_SETTER` + - Added `NanThrowError` with single Local<Value> argument + - Added `NanNewBufferHandle` with single uint32_t argument + - Added `NanHasInstance(Persistent<FunctionTemplate>&, Handle<Value>)` + - Added `Local<Function> NanCallback#GetFunction()` + - Added `NanCallback#Call(int, Local<Value>[])` + - Deprecated `NanCallback#Run(int, Local<Value>[])` in favour of Call diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/LICENSE.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..dddd13d5c1ddf8513fbfefe445e482ef2b16cbc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/LICENSE.md @@ -0,0 +1,13 @@ +The MIT License (MIT) +===================== + +Copyright (c) 2018 NAN contributors +----------------------------------- + +*NAN contributors listed at <https://github.com/nodejs/nan#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. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/README.md new file mode 100644 index 0000000000000000000000000000000000000000..b4851baab4f1ec82b9032a37beb243d8f3867742 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/README.md @@ -0,0 +1,456 @@ +Native Abstractions for Node.js +=============================== + +**A header file filled with macro and utility goodness for making add-on development for Node.js easier across versions 0.8, 0.10, 0.12, 1, 2, 3, 4, 5, 6, 7, 8 and 9.** + +***Current version: 2.10.0*** + +*(See [CHANGELOG.md](https://github.com/nodejs/nan/blob/master/CHANGELOG.md) for complete ChangeLog)* + +[](https://nodei.co/npm/nan/) [](https://nodei.co/npm/nan/) + +[](http://travis-ci.org/nodejs/nan) +[](https://ci.appveyor.com/project/RodVagg/nan) + +Thanks to the crazy changes in V8 (and some in Node core), keeping native addons compiling happily across versions, particularly 0.10 to 0.12 to 4.0, is a minor nightmare. The goal of this project is to store all logic necessary to develop native Node.js addons without having to inspect `NODE_MODULE_VERSION` and get yourself into a macro-tangle. + +This project also contains some helper utilities that make addon development a bit more pleasant. + + * **[News & Updates](#news)** + * **[Usage](#usage)** + * **[Example](#example)** + * **[API](#api)** + * **[Tests](#tests)** + * **[Knowns issues](#issues)** + * **[Governance & Contributing](#governance)** + +<a name="news"></a> + +## News & Updates + +<a name="usage"></a> + +## Usage + +Simply add **NAN** as a dependency in the *package.json* of your Node addon: + +``` bash +$ npm install --save nan +``` + +Pull in the path to **NAN** in your *binding.gyp* so that you can use `#include <nan.h>` in your *.cpp* files: + +``` python +"include_dirs" : [ + "<!(node -e \"require('nan')\")" +] +``` + +This works like a `-I<path-to-NAN>` when compiling your addon. + +<a name="example"></a> + +## Example + +Just getting started with Nan? Take a look at the **[Node Add-on Examples](https://github.com/nodejs/node-addon-examples)**. + +Refer to a [quick-start **Nan** Boilerplate](https://github.com/fcanas/node-native-boilerplate) for a ready-to-go project that utilizes basic Nan functionality. + +For a simpler example, see the **[async pi estimation example](https://github.com/nodejs/nan/tree/master/examples/async_pi_estimate)** in the examples directory for full code and an explanation of what this Monte Carlo Pi estimation example does. Below are just some parts of the full example that illustrate the use of **NAN**. + +Yet another example is **[nan-example-eol](https://github.com/CodeCharmLtd/nan-example-eol)**. It shows newline detection implemented as a native addon. + +Also take a look at our comprehensive **[C++ test suite](https://github.com/nodejs/nan/tree/master/test/cpp)** which has a plethora of code snippets for your pasting pleasure. + +<a name="api"></a> + +## API + +Additional to the NAN documentation below, please consult: + +* [The V8 Getting Started * Guide](https://github.com/v8/v8/wiki/Getting%20Started%20with%20Embedding) +* [The V8 Embedders * Guide](https://github.com/v8/v8/wiki/Embedder%27s%20Guide) +* [V8 API Documentation](http://v8docs.nodesource.com/) +* [Node Add-on Documentation](https://nodejs.org/api/addons.html) + +<!-- START API --> + +### JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - <a href="doc/methods.md#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a> + - <a href="doc/methods.md#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a> + - <a href="doc/methods.md#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a> +* **Method declarations** + - <a href="doc/methods.md#api_nan_method"><b>Method declaration</b></a> + - <a href="doc/methods.md#api_nan_getter"><b>Getter declaration</b></a> + - <a href="doc/methods.md#api_nan_setter"><b>Setter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_getter"><b>Property getter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_setter"><b>Property setter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_enumerator"><b>Property enumerator declaration</b></a> + - <a href="doc/methods.md#api_nan_property_deleter"><b>Property deleter declaration</b></a> + - <a href="doc/methods.md#api_nan_property_query"><b>Property query declaration</b></a> + - <a href="doc/methods.md#api_nan_index_getter"><b>Index getter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_setter"><b>Index setter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_enumerator"><b>Index enumerator declaration</b></a> + - <a href="doc/methods.md#api_nan_index_deleter"><b>Index deleter declaration</b></a> + - <a href="doc/methods.md#api_nan_index_query"><b>Index query declaration</b></a> +* Method and template helpers + - <a href="doc/methods.md#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a> + - <a href="doc/methods.md#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a> + - <a href="doc/methods.md#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a> + - <a href="doc/methods.md#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a> + - <a href="doc/methods.md#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a> + - <a href="doc/methods.md#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a> + +### Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - <a href="doc/scopes.md#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> + - <a href="doc/scopes.md#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). + +### Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - <a href="doc/persistent.md#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a> + - <a href="doc/persistent.md#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a> + - <a href="doc/persistent.md#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a> + - <a href="doc/persistent.md#api_nan_persistent"><b><code>Nan::Persistent</code></b></a> + - <a href="doc/persistent.md#api_nan_global"><b><code>Nan::Global</code></b></a> + - <a href="doc/persistent.md#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a> + - <a href="doc/persistent.md#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +### New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - <a href="doc/new.md#api_nan_new"><b><code>Nan::New()</code></b></a> + - <a href="doc/new.md#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a> + - <a href="doc/new.md#api_nan_null"><b><code>Nan::Null()</code></b></a> + - <a href="doc/new.md#api_nan_true"><b><code>Nan::True()</code></b></a> + - <a href="doc/new.md#api_nan_false"><b><code>Nan::False()</code></b></a> + - <a href="doc/new.md#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a> + + +### Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - <a href="doc/converters.md#api_nan_to"><b><code>Nan::To()</code></b></a> + +### Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - <a href="doc/maybe_types.md#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a> + - <a href="doc/maybe_types.md#api_nan_maybe"><b><code>Nan::Maybe</code></b></a> + - <a href="doc/maybe_types.md#api_nan_nothing"><b><code>Nan::Nothing</code></b></a> + - <a href="doc/maybe_types.md#api_nan_just"><b><code>Nan::Just</code></b></a> +* **Maybe Helpers** + - <a href="doc/maybe_types.md#api_nan_call"><b><code>Nan::Call()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_equals"><b><code>Nan::Equals()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set"><b><code>Nan::Set()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a> + - <a href="doc/maybe_types.md#api_nan_get"><b><code>Nan::Get()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has"><b><code>Nan::Has()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_delete"><b><code>Nan::Delete()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a> + - <a href="doc/maybe_types.md#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a> + +### Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - <a href="doc/script.md#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> + - <a href="doc/script.md#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> + + +### JSON + +The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. + + - <a href="doc/json.md#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> + - <a href="doc/json.md#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> + +Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. + +### Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - <a href="doc/errors.md#api_nan_error"><b><code>Nan::Error()</code></b></a> + - <a href="doc/errors.md#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a> + - <a href="doc/errors.md#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a> + - <a href="doc/errors.md#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a> + - <a href="doc/errors.md#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a> + - <a href="doc/errors.md#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a> + - <a href="doc/errors.md#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a> + - <a href="doc/errors.md#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a> + - <a href="doc/errors.md#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a> + + +### Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - <a href="doc/buffers.md#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> + - <a href="doc/buffers.md#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> + - <a href="doc/buffers.md#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> + +### Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - <a href="doc/callback.md#api_nan_callback"><b><code>Nan::Callback</code></b></a> + +### Asynchronous work helpers + +`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. + + - <a href="doc/asyncworker.md#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a> + - <a href="doc/asyncworker.md#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a> + +### Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - <a href="doc/string_bytes.md#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> + - <a href="doc/string_bytes.md#api_nan_encode"><b><code>Nan::Encode()</code></b></a> + - <a href="doc/string_bytes.md#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> + - <a href="doc/string_bytes.md#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> + + +### Object Wrappers + +The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. + + - <a href="doc/object_wrappers.md#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a> + + +### V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - <a href="doc/v8_internals.md#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a> + - <a href="doc/v8_internals.md#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a> + + +### Miscellaneous V8 Helpers + + - <a href="doc/v8_misc.md#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> + - <a href="doc/v8_misc.md#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> + - <a href="doc/v8_misc.md#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> + + +### Miscellaneous Node Helpers + + - <a href="doc/node_misc.md#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a> + - <a href="doc/node_misc.md#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a> + - <a href="doc/node_misc.md#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a> + - <a href="doc/node_misc.md#api_nan_export"><b><code>Nan::Export()</code></b></a> + +<!-- END API --> + + +<a name="tests"></a> + +### Tests + +To run the NAN tests do: + +``` sh +npm install +npm run-script rebuild-tests +npm test +``` + +Or just: + +``` sh +npm install +make test +``` + +<a name="issues"></a> + +## Known issues + +### Compiling against Node.js 0.12 on OSX + +With new enough compilers available on OSX, the versions of V8 headers corresponding to Node.js 0.12 +do not compile anymore. The error looks something like: + +``` +⯠CXX(target) Release/obj.target/accessors/cpp/accessors.o +In file included from ../cpp/accessors.cpp:9: +In file included from ../../nan.h:51: +In file included from /Users/ofrobots/.node-gyp/0.12.18/include/node/node.h:61: +/Users/ofrobots/.node-gyp/0.12.18/include/node/v8.h:5800:54: error: 'CreateHandle' is a protected member of 'v8::HandleScope' + return Handle<T>(reinterpret_cast<T*>(HandleScope::CreateHandle( + ~~~~~~~~~~~~~^~~~~~~~~~~~ +``` + +This can be worked around by patching your local versions of v8.h corresponding to Node 0.12 to make +`v8::Handle` a friend of `v8::HandleScope`. Since neither Node.js not V8 support this release line anymore +this patch cannot be released by either project in an official release. + +For this reason, we do not test against Node.js 0.12 on OSX in this project's CI. If you need to support +that configuration, you will need to either get an older compiler, or apply a source patch to the version +of V8 headers as a workaround. + +<a name="governance"></a> + +## Governance & Contributing + +NAN is governed by the [Node.js Addon API Working Group](https://github.com/nodejs/CTC/blob/master/WORKING_GROUPS.md#addon-api) + +### Addon API Working Group (WG) + +The NAN project is jointly governed by a Working Group which is responsible for high-level guidance of the project. + +Members of the WG are also known as Collaborators, there is no distinction between the two, unlike other Node.js projects. + +The WG has final authority over this project including: + +* Technical direction +* Project governance and process (including this policy) +* Contribution policy +* GitHub repository hosting +* Maintaining the list of additional Collaborators + +For the current list of WG members, see the project [README.md](./README.md#collaborators). + +Individuals making significant and valuable contributions are made members of the WG and given commit-access to the project. These individuals are identified by the WG and their addition to the WG is discussed via GitHub and requires unanimous consensus amongst those WG members participating in the discussion with a quorum of 50% of WG members required for acceptance of the vote. + +_Note:_ If you make a significant contribution and are not considered for commit-access log an issue or contact a WG member directly. + +For the current list of WG members / Collaborators, see the project [README.md](./README.md#collaborators). + +### Consensus Seeking Process + +The WG follows a [Consensus Seeking](http://en.wikipedia.org/wiki/Consensus-seeking_decision-making) decision making model. + +Modifications of the contents of the NAN repository are made on a collaborative basis. Anybody with a GitHub account may propose a modification via pull request and it will be considered by the WG. All pull requests must be reviewed and accepted by a WG member with sufficient expertise who is able to take full responsibility for the change. In the case of pull requests proposed by an existing WG member, an additional WG member is required for sign-off. Consensus should be sought if additional WG members participate and there is disagreement around a particular modification. + +If a change proposal cannot reach a consensus, a WG member can call for a vote amongst the members of the WG. Simple majority wins. + +<a id="developers-certificate-of-origin"></a> + +## Developer's Certificate of Origin 1.1 + +By making a contribution to this project, I certify that: + +* (a) The contribution was created in whole or in part by me and I + have the right to submit it under the open source license + indicated in the file; or + +* (b) The contribution is based upon previous work that, to the best + of my knowledge, is covered under an appropriate open source + license and I have the right under that license to submit that + work with modifications, whether created in whole or in part + by me, under the same open source license (unless I am + permitted to submit under a different license), as indicated + in the file; or + +* (c) The contribution was provided directly to me by some other + person who certified (a), (b) or (c) and I have not modified + it. + +* (d) I understand and agree that this project and the contribution + are public and that a record of the contribution (including all + personal information I submit with it, including my sign-off) is + maintained indefinitely and may be redistributed consistent with + this project or the open source license(s) involved. + +<a name="collaborators"></a> + +### WG Members / Collaborators + +<table><tbody> +<tr><th align="left">Rod Vagg</th><td><a href="https://github.com/rvagg">GitHub/rvagg</a></td><td><a href="http://twitter.com/rvagg">Twitter/@rvagg</a></td></tr> +<tr><th align="left">Benjamin Byholm</th><td><a href="https://github.com/kkoopa/">GitHub/kkoopa</a></td><td>-</td></tr> +<tr><th align="left">Trevor Norris</th><td><a href="https://github.com/trevnorris">GitHub/trevnorris</a></td><td><a href="http://twitter.com/trevnorris">Twitter/@trevnorris</a></td></tr> +<tr><th align="left">Nathan Rajlich</th><td><a href="https://github.com/TooTallNate">GitHub/TooTallNate</a></td><td><a href="http://twitter.com/TooTallNate">Twitter/@TooTallNate</a></td></tr> +<tr><th align="left">Brett Lawson</th><td><a href="https://github.com/brett19">GitHub/brett19</a></td><td><a href="http://twitter.com/brett19x">Twitter/@brett19x</a></td></tr> +<tr><th align="left">Ben Noordhuis</th><td><a href="https://github.com/bnoordhuis">GitHub/bnoordhuis</a></td><td><a href="http://twitter.com/bnoordhuis">Twitter/@bnoordhuis</a></td></tr> +<tr><th align="left">David Siegel</th><td><a href="https://github.com/agnat">GitHub/agnat</a></td><td><a href="http://twitter.com/agnat">Twitter/@agnat</a></td></tr> +<tr><th align="left">Michael Ira Krufky</th><td><a href="https://github.com/mkrufky">GitHub/mkrufky</a></td><td><a href="http://twitter.com/mkrufky">Twitter/@mkrufky</a></td></tr> +</tbody></table> + +## Licence & copyright + +Copyright (c) 2018 NAN WG Members / Collaborators (listed above). + +Native Abstractions for Node.js is licensed under an MIT license. All rights not explicitly granted in the MIT license are reserved. See the included LICENSE file for more details. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/asyncworker.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/asyncworker.md new file mode 100644 index 0000000000000000000000000000000000000000..239de801c1e5a82069ba19f1905babd36150dda5 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/asyncworker.md @@ -0,0 +1,146 @@ +## Asynchronous work helpers + +`Nan::AsyncWorker`, `Nan::AsyncProgressWorker` and `Nan::AsyncProgressQueueWorker` are helper classes that make working with asynchronous code easier. + + - <a href="#api_nan_async_worker"><b><code>Nan::AsyncWorker</code></b></a> + - <a href="#api_nan_async_progress_worker"><b><code>Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker</code></b></a> + - <a href="#api_nan_async_progress_queue_worker"><b><code>Nan::AsyncProgressQueueWorker</code></b></a> + - <a href="#api_nan_async_queue_worker"><b><code>Nan::AsyncQueueWorker</code></b></a> + +<a name="api_nan_async_worker"></a> +### Nan::AsyncWorker + +`Nan::AsyncWorker` is an _abstract_ class that you can subclass to have much of the annoying asynchronous queuing and handling taken care of for you. It can even store arbitrary V8 objects for you and have them persist while the asynchronous work is in progress. + +This class internally handles the details of creating an [`AsyncResource`][AsyncResource], and running the callback in the +correct async context. To be able to identify the async resources created by this class in async-hooks, provide a +`resource_name` to the constructor. It is recommended that the module name be used as a prefix to the `resource_name` to avoid +collisions in the names. For more details see [`AsyncResource`][AsyncResource] documentation. The `resource_name` needs to stay valid for the lifetime of the worker instance. + +Definition: + +```c++ +class AsyncWorker { + public: + explicit AsyncWorker(Callback *callback_, const char* resource_name = "nan:AsyncWorker"); + + virtual ~AsyncWorker(); + + virtual void WorkComplete(); + + void SaveToPersistent(const char *key, const v8::Local<v8::Value> &value); + + void SaveToPersistent(const v8::Local<v8::String> &key, + const v8::Local<v8::Value> &value); + + void SaveToPersistent(uint32_t index, + const v8::Local<v8::Value> &value); + + v8::Local<v8::Value> GetFromPersistent(const char *key) const; + + v8::Local<v8::Value> GetFromPersistent(const v8::Local<v8::String> &key) const; + + v8::Local<v8::Value> GetFromPersistent(uint32_t index) const; + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy(); + + protected: + Persistent<v8::Object> persistentHandle; + + Callback *callback; + + virtual void HandleOKCallback(); + + virtual void HandleErrorCallback(); + + void SetErrorMessage(const char *msg); + + const char* ErrorMessage(); +}; +``` + +<a name="api_nan_async_progress_worker"></a> +### Nan::AsyncProgressWorkerBase & Nan::AsyncProgressWorker + +`Nan::AsyncProgressWorkerBase` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. + +Previously the definiton of `Nan::AsyncProgressWorker` only allowed sending `const char` data. Now extending `Nan::AsyncProgressWorker` will yield an instance of the implicit `Nan::AsyncProgressWorkerBase` template with type `<char>` for compatibility. + +`Nan::AsyncProgressWorkerBase` & `Nan::AsyncProgressWorker` is intended for best-effort delivery of nonessential progress messages, e.g. a progress bar. The last event sent before the main thread is woken will be delivered. + +Definition: + +```c++ +template<class T> +class AsyncProgressWorkerBase<T> : public AsyncWorker { + public: + explicit AsyncProgressWorkerBase(Callback *callback_, const char* resource_name = ...); + + virtual ~AsyncProgressWorkerBase(); + + void WorkProgress(); + + class ExecutionProgress { + public: + void Signal() const; + void Send(const T* data, size_t count) const; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + + virtual void HandleProgressCallback(const T *data, size_t count) = 0; + + virtual void Destroy(); +}; + +typedef AsyncProgressWorkerBase<T> AsyncProgressWorker; +``` + +<a name="api_nan_async_progress_queue_worker"></a> +### Nan::AsyncProgressQueueWorker + +`Nan::AsyncProgressQueueWorker` is an _abstract_ class template that extends `Nan::AsyncWorker` and adds additional progress reporting callbacks that can be used during the asynchronous work execution to provide progress data back to JavaScript. + +`Nan::AsyncProgressQueueWorker` behaves exactly the same as `Nan::AsyncProgressWorker`, except all events are queued and delivered to the main thread. + +Definition: + +```c++ +template<class T> +class AsyncProgressQueueWorker<T> : public AsyncWorker { + public: + explicit AsyncProgressQueueWorker(Callback *callback_, const char* resource_name = "nan:AsyncProgressQueueWorker"); + + virtual ~AsyncProgressQueueWorker(); + + void WorkProgress(); + + class ExecutionProgress { + public: + void Send(const T* data, size_t count) const; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + + virtual void HandleProgressCallback(const T *data, size_t count) = 0; + + virtual void Destroy(); +}; +``` + +<a name="api_nan_async_queue_worker"></a> +### Nan::AsyncQueueWorker + +`Nan::AsyncQueueWorker` will run a `Nan::AsyncWorker` asynchronously via libuv. Both the `execute` and `after_work` steps are taken care of for you. Most of the logic for this is embedded in `Nan::AsyncWorker`. + +Definition: + +```c++ +void AsyncQueueWorker(AsyncWorker *); +``` + +[AsyncResource]: "node_misc.html#api_nan_asyncresource" diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/buffers.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/buffers.md new file mode 100644 index 0000000000000000000000000000000000000000..8d8d25cf75a854d989ef7bc498caa7721913b89a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/buffers.md @@ -0,0 +1,54 @@ +## Buffers + +NAN's `node::Buffer` helpers exist as the API has changed across supported Node versions. Use these methods to ensure compatibility. + + - <a href="#api_nan_new_buffer"><b><code>Nan::NewBuffer()</code></b></a> + - <a href="#api_nan_copy_buffer"><b><code>Nan::CopyBuffer()</code></b></a> + - <a href="#api_nan_free_callback"><b><code>Nan::FreeCallback()</code></b></a> + +<a name="api_nan_new_buffer"></a> +### Nan::NewBuffer() + +Allocate a new `node::Buffer` object with the specified size and optional data. Calls `node::Buffer::New()`. + +Note that when creating a `Buffer` using `Nan::NewBuffer()` and an existing `char*`, it is assumed that the ownership of the pointer is being transferred to the new `Buffer` for management. +When a `node::Buffer` instance is garbage collected and a `FreeCallback` has not been specified, `data` will be disposed of via a call to `free()`. +You _must not_ free the memory space manually once you have created a `Buffer` in this way. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(uint32_t size) +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char* data, uint32_t size) +Nan::MaybeLocal<v8::Object> Nan::NewBuffer(char *data, + size_t length, + Nan::FreeCallback callback, + void *hint) +``` + + +<a name="api_nan_copy_buffer"></a> +### Nan::CopyBuffer() + +Similar to [`Nan::NewBuffer()`](#api_nan_new_buffer) except that an implicit memcpy will occur within Node. Calls `node::Buffer::Copy()`. + +Management of the `char*` is left to the user, you should manually free the memory space if necessary as the new `Buffer` will have its own copy. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::CopyBuffer(const char *data, uint32_t size) +``` + + +<a name="api_nan_free_callback"></a> +### Nan::FreeCallback() + +A free callback that can be provided to [`Nan::NewBuffer()`](#api_nan_new_buffer). +The supplied callback will be invoked when the `Buffer` undergoes garbage collection. + +Signature: + +```c++ +typedef void (*FreeCallback)(char *data, void *hint); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/callback.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/callback.md new file mode 100644 index 0000000000000000000000000000000000000000..f7af0bfd9d8281f2eb7e16fc57e787ce54ebeda2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/callback.md @@ -0,0 +1,76 @@ +## Nan::Callback + +`Nan::Callback` makes it easier to use `v8::Function` handles as callbacks. A class that wraps a `v8::Function` handle, protecting it from garbage collection and making it particularly useful for storage and use across asynchronous execution. + + - <a href="#api_nan_callback"><b><code>Nan::Callback</code></b></a> + +<a name="api_nan_callback"></a> +### Nan::Callback + +```c++ +class Callback { + public: + Callback(); + + explicit Callback(const v8::Local<v8::Function> &fn); + + ~Callback(); + + bool operator==(const Callback &other) const; + + bool operator!=(const Callback &other) const; + + v8::Local<v8::Function> operator*() const; + + MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, + v8::Local<v8::Object> target, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + MaybeLocal<v8::Value> operator()(AsyncResource* async_resource, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + void SetFunction(const v8::Local<v8::Function> &fn); + + v8::Local<v8::Function> GetFunction() const; + + bool IsEmpty() const; + + void Reset(const v8::Local<v8::Function> &fn); + + void Reset(); + + MaybeLocal<v8::Value> Call(v8::Local<v8::Object> target, + int argc, + v8::Local<v8::Value> argv[], + AsyncResource* async_resource) const; + MaybeLocal<v8::Value> Call(int argc, + v8::Local<v8::Value> argv[], + AsyncResource* async_resource) const; + + // Deprecated versions. Use the versions that accept an async_resource instead + // as they run the callback in the correct async context as specified by the + // resource. If you want to call a synchronous JS function (i.e. on a + // non-empty JS stack), you can use Nan::Call instead. + v8::Local<v8::Value> operator()(v8::Local<v8::Object> target, + int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + + v8::Local<v8::Value> operator()(int argc = 0, + v8::Local<v8::Value> argv[] = 0) const; + v8::Local<v8::Value> Call(v8::Local<v8::Object> target, + int argc, + v8::Local<v8::Value> argv[]) const; + + v8::Local<v8::Value> Call(int argc, v8::Local<v8::Value> argv[]) const; +}; +``` + +Example usage: + +```c++ +v8::Local<v8::Function> function; +Nan::Callback callback(function); +callback.Call(0, 0); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/converters.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/converters.md new file mode 100644 index 0000000000000000000000000000000000000000..d20861b5935b6208b594b91f67cabd27a2bb5558 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/converters.md @@ -0,0 +1,41 @@ +## Converters + +NAN contains functions that convert `v8::Value`s to other `v8::Value` types and native types. Since type conversion is not guaranteed to succeed, they return `Nan::Maybe` types. These converters can be used in place of `value->ToX()` and `value->XValue()` (where `X` is one of the types, e.g. `Boolean`) in a way that provides a consistent interface across V8 versions. Newer versions of V8 use the new `v8::Maybe` and `v8::MaybeLocal` types for these conversions, older versions don't have this functionality so it is provided by NAN. + + - <a href="#api_nan_to"><b><code>Nan::To()</code></b></a> + +<a name="api_nan_to"></a> +### Nan::To() + +Converts a `v8::Local<v8::Value>` to a different subtype of `v8::Value` or to a native data type. Returns a `Nan::MaybeLocal<>` or a `Nan::Maybe<>` accordingly. + +See [maybe_types.md](./maybe_types.md) for more information on `Nan::Maybe` types. + +Signatures: + +```c++ +// V8 types +Nan::MaybeLocal<v8::Boolean> Nan::To<v8::Boolean>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Int32> Nan::To<v8::Int32>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Integer> Nan::To<v8::Integer>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Object> Nan::To<v8::Object>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Number> Nan::To<v8::Number>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::String> Nan::To<v8::String>(v8::Local<v8::Value> val); +Nan::MaybeLocal<v8::Uint32> Nan::To<v8::Uint32>(v8::Local<v8::Value> val); + +// Native types +Nan::Maybe<bool> Nan::To<bool>(v8::Local<v8::Value> val); +Nan::Maybe<double> Nan::To<double>(v8::Local<v8::Value> val); +Nan::Maybe<int32_t> Nan::To<int32_t>(v8::Local<v8::Value> val); +Nan::Maybe<int64_t> Nan::To<int64_t>(v8::Local<v8::Value> val); +Nan::Maybe<uint32_t> Nan::To<uint32_t>(v8::Local<v8::Value> val); +``` + +### Example + +```c++ +v8::Local<v8::Value> val; +Nan::MaybeLocal<v8::String> str = Nan::To<v8::String>(val); +Nan::Maybe<double> d = Nan::To<double>(val); +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/errors.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/errors.md new file mode 100644 index 0000000000000000000000000000000000000000..b93b3535c7f9e4bbf5077da17f3cf383bb0cf1e6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/errors.md @@ -0,0 +1,226 @@ +## Errors + +NAN includes helpers for creating, throwing and catching Errors as much of this functionality varies across the supported versions of V8 and must be abstracted. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Also consult the V8 Embedders Guide section on [Exceptions](https://developers.google.com/v8/embed#exceptions) for more information. + + - <a href="#api_nan_error"><b><code>Nan::Error()</code></b></a> + - <a href="#api_nan_range_error"><b><code>Nan::RangeError()</code></b></a> + - <a href="#api_nan_reference_error"><b><code>Nan::ReferenceError()</code></b></a> + - <a href="#api_nan_syntax_error"><b><code>Nan::SyntaxError()</code></b></a> + - <a href="#api_nan_type_error"><b><code>Nan::TypeError()</code></b></a> + - <a href="#api_nan_throw_error"><b><code>Nan::ThrowError()</code></b></a> + - <a href="#api_nan_throw_range_error"><b><code>Nan::ThrowRangeError()</code></b></a> + - <a href="#api_nan_throw_reference_error"><b><code>Nan::ThrowReferenceError()</code></b></a> + - <a href="#api_nan_throw_syntax_error"><b><code>Nan::ThrowSyntaxError()</code></b></a> + - <a href="#api_nan_throw_type_error"><b><code>Nan::ThrowTypeError()</code></b></a> + - <a href="#api_nan_fatal_exception"><b><code>Nan::FatalException()</code></b></a> + - <a href="#api_nan_errno_exception"><b><code>Nan::ErrnoException()</code></b></a> + - <a href="#api_nan_try_catch"><b><code>Nan::TryCatch</code></b></a> + + +<a name="api_nan_error"></a> +### Nan::Error() + +Create a new Error object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an Error object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::Error(const char *msg); +v8::Local<v8::Value> Nan::Error(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_range_error"></a> +### Nan::RangeError() + +Create a new RangeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an RangeError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::RangeError(const char *msg); +v8::Local<v8::Value> Nan::RangeError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_reference_error"></a> +### Nan::ReferenceError() + +Create a new ReferenceError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an ReferenceError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::ReferenceError(const char *msg); +v8::Local<v8::Value> Nan::ReferenceError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_syntax_error"></a> +### Nan::SyntaxError() + +Create a new SyntaxError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an SyntaxError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::SyntaxError(const char *msg); +v8::Local<v8::Value> Nan::SyntaxError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_type_error"></a> +### Nan::TypeError() + +Create a new TypeError object using the [v8::Exception](https://v8docs.nodesource.com/io.js-3.3/da/d6a/classv8_1_1_exception.html) class in a way that is compatible across the supported versions of V8. + +Note that an TypeError object is simply a specialized form of `v8::Value`. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::TypeError(const char *msg); +v8::Local<v8::Value> Nan::TypeError(v8::Local<v8::String> msg); +``` + + +<a name="api_nan_throw_error"></a> +### Nan::ThrowError() + +Throw an Error object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new Error object will be created. + +Signature: + +```c++ +void Nan::ThrowError(const char *msg); +void Nan::ThrowError(v8::Local<v8::String> msg); +void Nan::ThrowError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_range_error"></a> +### Nan::ThrowRangeError() + +Throw an RangeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new RangeError object will be created. + +Signature: + +```c++ +void Nan::ThrowRangeError(const char *msg); +void Nan::ThrowRangeError(v8::Local<v8::String> msg); +void Nan::ThrowRangeError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_reference_error"></a> +### Nan::ThrowReferenceError() + +Throw an ReferenceError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new ReferenceError object will be created. + +Signature: + +```c++ +void Nan::ThrowReferenceError(const char *msg); +void Nan::ThrowReferenceError(v8::Local<v8::String> msg); +void Nan::ThrowReferenceError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_syntax_error"></a> +### Nan::ThrowSyntaxError() + +Throw an SyntaxError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new SyntaxError object will be created. + +Signature: + +```c++ +void Nan::ThrowSyntaxError(const char *msg); +void Nan::ThrowSyntaxError(v8::Local<v8::String> msg); +void Nan::ThrowSyntaxError(v8::Local<v8::Value> error); +``` + + +<a name="api_nan_throw_type_error"></a> +### Nan::ThrowTypeError() + +Throw an TypeError object (a specialized `v8::Value` as above) in the current context. If a `msg` is provided, a new TypeError object will be created. + +Signature: + +```c++ +void Nan::ThrowTypeError(const char *msg); +void Nan::ThrowTypeError(v8::Local<v8::String> msg); +void Nan::ThrowTypeError(v8::Local<v8::Value> error); +``` + +<a name="api_nan_fatal_exception"></a> +### Nan::FatalException() + +Replaces `node::FatalException()` which has a different API across supported versions of Node. For use with [`Nan::TryCatch`](#api_nan_try_catch). + +Signature: + +```c++ +void Nan::FatalException(const Nan::TryCatch& try_catch); +``` + +<a name="api_nan_errno_exception"></a> +### Nan::ErrnoException() + +Replaces `node::ErrnoException()` which has a different API across supported versions of Node. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::ErrnoException(int errorno, + const char* syscall = NULL, + const char* message = NULL, + const char* path = NULL); +``` + + +<a name="api_nan_try_catch"></a> +### Nan::TryCatch + +A simple wrapper around [`v8::TryCatch`](https://v8docs.nodesource.com/io.js-3.3/d4/dc6/classv8_1_1_try_catch.html) compatible with all supported versions of V8. Can be used as a direct replacement in most cases. See also [`Nan::FatalException()`](#api_nan_fatal_exception) for an internal use compatible with `node::FatalException`. + +Signature: + +```c++ +class Nan::TryCatch { + public: + Nan::TryCatch(); + + bool HasCaught() const; + + bool CanContinue() const; + + v8::Local<v8::Value> ReThrow(); + + v8::Local<v8::Value> Exception() const; + + // Nan::MaybeLocal for older versions of V8 + v8::MaybeLocal<v8::Value> StackTrace() const; + + v8::Local<v8::Message> Message() const; + + void Reset(); + + void SetVerbose(bool value); + + void SetCaptureMessage(bool value); +}; +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/json.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/json.md new file mode 100644 index 0000000000000000000000000000000000000000..c916c4d158cdcf926016a4e9e992ca3f3386fda0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/json.md @@ -0,0 +1,62 @@ +## JSON + +The _JSON_ object provides the c++ versions of the methods offered by the `JSON` object in javascript. V8 exposes these methods via the `v8::JSON` object. + + - <a href="#api_nan_json_parse"><b><code>Nan::JSON.Parse</code></b></a> + - <a href="#api_nan_json_stringify"><b><code>Nan::JSON.Stringify</code></b></a> + +Refer to the V8 JSON object in the [V8 documentation](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html) for more information about these methods and their arguments. + +<a name="api_nan_json_parse"></a> + +### Nan::JSON.Parse + +A simple wrapper around [`v8::JSON::Parse`](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html#a936310d2540fb630ed37d3ee3ffe4504). + +Definition: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::JSON::Parse(v8::Local<v8::String> json_string); +``` + +Use `JSON.Parse(json_string)` to parse a string into a `v8::Value`. + +Example: + +```c++ +v8::Local<v8::String> json_string = Nan::New("{ \"JSON\": \"object\" }").ToLocalChecked(); + +Nan::JSON NanJSON; +Nan::MaybeLocal<v8::Value> result = NanJSON.Parse(json_string); +if (!result.IsEmpty()) { + v8::Local<v8::Value> val = result.ToLocalChecked(); +} +``` + +<a name="api_nan_json_stringify"></a> + +### Nan::JSON.Stringify + +A simple wrapper around [`v8::JSON::Stringify`](https://v8docs.nodesource.com/node-7.4/da/d6f/classv8_1_1_j_s_o_n.html#a44b255c3531489ce43f6110209138860). + +Definition: + +```c++ +Nan::MaybeLocal<v8::String> Nan::JSON::Stringify(v8::Local<v8::Object> json_object, v8::Local<v8::String> gap = v8::Local<v8::String>()); +``` + +Use `JSON.Stringify(value)` to stringify a `v8::Object`. + +Example: + +```c++ +// using `v8::Local<v8::Value> val` from the `JSON::Parse` example +v8::Local<v8::Object> obj = Nan::To<v8::Object>(val).ToLocalChecked(); + +Nan::JSON NanJSON; +Nan::MaybeLocal<v8::String> result = NanJSON.Stringify(obj); +if (!result.IsEmpty()) { + v8::Local<v8::String> stringified = result.ToLocalChecked(); +} +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/maybe_types.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/maybe_types.md new file mode 100644 index 0000000000000000000000000000000000000000..f11df56d9297ad03f154281e17a268aa60f98f80 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/maybe_types.md @@ -0,0 +1,583 @@ +## Maybe Types + +The `Nan::MaybeLocal` and `Nan::Maybe` types are monads that encapsulate `v8::Local` handles that _may be empty_. + +* **Maybe Types** + - <a href="#api_nan_maybe_local"><b><code>Nan::MaybeLocal</code></b></a> + - <a href="#api_nan_maybe"><b><code>Nan::Maybe</code></b></a> + - <a href="#api_nan_nothing"><b><code>Nan::Nothing</code></b></a> + - <a href="#api_nan_just"><b><code>Nan::Just</code></b></a> +* **Maybe Helpers** + - <a href="#api_nan_call"><b><code>Nan::Call()</code></b></a> + - <a href="#api_nan_to_detail_string"><b><code>Nan::ToDetailString()</code></b></a> + - <a href="#api_nan_to_array_index"><b><code>Nan::ToArrayIndex()</code></b></a> + - <a href="#api_nan_equals"><b><code>Nan::Equals()</code></b></a> + - <a href="#api_nan_new_instance"><b><code>Nan::NewInstance()</code></b></a> + - <a href="#api_nan_get_function"><b><code>Nan::GetFunction()</code></b></a> + - <a href="#api_nan_set"><b><code>Nan::Set()</code></b></a> + - <a href="#api_nan_define_own_property"><b><code>Nan::DefineOwnProperty()</code></b></a> + - <a href="#api_nan_force_set"><del><b><code>Nan::ForceSet()</code></b></del></a> + - <a href="#api_nan_get"><b><code>Nan::Get()</code></b></a> + - <a href="#api_nan_get_property_attribute"><b><code>Nan::GetPropertyAttributes()</code></b></a> + - <a href="#api_nan_has"><b><code>Nan::Has()</code></b></a> + - <a href="#api_nan_delete"><b><code>Nan::Delete()</code></b></a> + - <a href="#api_nan_get_property_names"><b><code>Nan::GetPropertyNames()</code></b></a> + - <a href="#api_nan_get_own_property_names"><b><code>Nan::GetOwnPropertyNames()</code></b></a> + - <a href="#api_nan_set_prototype"><b><code>Nan::SetPrototype()</code></b></a> + - <a href="#api_nan_object_proto_to_string"><b><code>Nan::ObjectProtoToString()</code></b></a> + - <a href="#api_nan_has_own_property"><b><code>Nan::HasOwnProperty()</code></b></a> + - <a href="#api_nan_has_real_named_property"><b><code>Nan::HasRealNamedProperty()</code></b></a> + - <a href="#api_nan_has_real_indexed_property"><b><code>Nan::HasRealIndexedProperty()</code></b></a> + - <a href="#api_nan_has_real_named_callback_property"><b><code>Nan::HasRealNamedCallbackProperty()</code></b></a> + - <a href="#api_nan_get_real_named_property_in_prototype_chain"><b><code>Nan::GetRealNamedPropertyInPrototypeChain()</code></b></a> + - <a href="#api_nan_get_real_named_property"><b><code>Nan::GetRealNamedProperty()</code></b></a> + - <a href="#api_nan_call_as_function"><b><code>Nan::CallAsFunction()</code></b></a> + - <a href="#api_nan_call_as_constructor"><b><code>Nan::CallAsConstructor()</code></b></a> + - <a href="#api_nan_get_source_line"><b><code>Nan::GetSourceLine()</code></b></a> + - <a href="#api_nan_get_line_number"><b><code>Nan::GetLineNumber()</code></b></a> + - <a href="#api_nan_get_start_column"><b><code>Nan::GetStartColumn()</code></b></a> + - <a href="#api_nan_get_end_column"><b><code>Nan::GetEndColumn()</code></b></a> + - <a href="#api_nan_clone_element_at"><b><code>Nan::CloneElementAt()</code></b></a> + - <a href="#api_nan_has_private"><b><code>Nan::HasPrivate()</code></b></a> + - <a href="#api_nan_get_private"><b><code>Nan::GetPrivate()</code></b></a> + - <a href="#api_nan_set_private"><b><code>Nan::SetPrivate()</code></b></a> + - <a href="#api_nan_delete_private"><b><code>Nan::DeletePrivate()</code></b></a> + - <a href="#api_nan_make_maybe"><b><code>Nan::MakeMaybe()</code></b></a> + +<a name="api_nan_maybe_local"></a> +### Nan::MaybeLocal + +A `Nan::MaybeLocal<T>` is a wrapper around [`v8::Local<T>`](https://v8docs.nodesource.com/io.js-3.3/de/deb/classv8_1_1_local.html) that enforces a check that determines whether the `v8::Local<T>` is empty before it can be used. + +If an API method returns a `Nan::MaybeLocal`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, an empty `Nan::MaybeLocal` is returned. + +Definition: + +```c++ +template<typename T> class Nan::MaybeLocal { + public: + MaybeLocal(); + + template<typename S> MaybeLocal(v8::Local<S> that); + + bool IsEmpty() const; + + template<typename S> bool ToLocal(v8::Local<S> *out); + + // Will crash if the MaybeLocal<> is empty. + v8::Local<T> ToLocalChecked(); + + template<typename S> v8::Local<S> FromMaybe(v8::Local<S> default_value) const; +}; +``` + +See the documentation for [`v8::MaybeLocal`](https://v8docs.nodesource.com/io.js-3.3/d8/d7d/classv8_1_1_maybe_local.html) for further details. + +<a name="api_nan_maybe"></a> +### Nan::Maybe + +A simple `Nan::Maybe` type, representing an object which may or may not have a value, see https://hackage.haskell.org/package/base/docs/Data-Maybe.html. + +If an API method returns a `Nan::Maybe<>`, the API method can potentially fail either because an exception is thrown, or because an exception is pending, e.g. because a previous API call threw an exception that hasn't been caught yet, or because a `v8::TerminateExecution` exception was thrown. In that case, a "Nothing" value is returned. + +Definition: + +```c++ +template<typename T> class Nan::Maybe { + public: + bool IsNothing() const; + bool IsJust() const; + + // Will crash if the Maybe<> is nothing. + T FromJust(); + + T FromMaybe(const T& default_value); + + bool operator==(const Maybe &other); + + bool operator!=(const Maybe &other); +}; +``` + +See the documentation for [`v8::Maybe`](https://v8docs.nodesource.com/io.js-3.3/d9/d4b/classv8_1_1_maybe.html) for further details. + +<a name="api_nan_nothing"></a> +### Nan::Nothing + +Construct an empty `Nan::Maybe` type representing _nothing_. + +```c++ +template<typename T> Nan::Maybe<T> Nan::Nothing(); +``` + +<a name="api_nan_just"></a> +### Nan::Just + +Construct a `Nan::Maybe` type representing _just_ a value. + +```c++ +template<typename T> Nan::Maybe<T> Nan::Just(const T &t); +``` + +<a name="api_nan_call"></a> +### Nan::Call() + +A helper method for calling a synchronous [`v8::Function#Call()`](https://v8docs.nodesource.com/io.js-3.3/d5/d54/classv8_1_1_function.html#a468a89f737af0612db10132799c827c0) in a way compatible across supported versions of V8. + +For asynchronous callbacks, use Nan::Callback::Call along with an AsyncResource. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::Call(v8::Local<v8::Function> fun, v8::Local<v8::Object> recv, int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, v8::Local<v8::Object> recv, + int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Value> Nan::Call(const Nan::Callback& callback, int argc, v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_to_detail_string"></a> +### Nan::ToDetailString() + +A helper method for calling [`v8::Value#ToDetailString()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#a2f9770296dc2c8d274bc8cc0dca243e5) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::ToDetailString(v8::Local<v8::Value> val); +``` + + +<a name="api_nan_to_array_index"></a> +### Nan::ToArrayIndex() + +A helper method for calling [`v8::Value#ToArrayIndex()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#acc5bbef3c805ec458470c0fcd6f13493) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Uint32> Nan::ToArrayIndex(v8::Local<v8::Value> val); +``` + + +<a name="api_nan_equals"></a> +### Nan::Equals() + +A helper method for calling [`v8::Value#Equals()`](https://v8docs.nodesource.com/io.js-3.3/dc/d0a/classv8_1_1_value.html#a0d9616ab2de899d4e3047c30a10c9285) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)); +``` + + +<a name="api_nan_new_instance"></a> +### Nan::NewInstance() + +A helper method for calling [`v8::Function#NewInstance()`](https://v8docs.nodesource.com/io.js-3.3/d5/d54/classv8_1_1_function.html#a691b13f7a553069732cbacf5ac8c62ec) and [`v8::ObjectTemplate#NewInstance()`](https://v8docs.nodesource.com/io.js-3.3/db/d5f/classv8_1_1_object_template.html#ad605a7543cfbc5dab54cdb0883d14ae4) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h); +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::Function> h, int argc, v8::Local<v8::Value> argv[]); +Nan::MaybeLocal<v8::Object> Nan::NewInstance(v8::Local<v8::ObjectTemplate> h); +``` + + +<a name="api_nan_get_function"></a> +### Nan::GetFunction() + +A helper method for calling [`v8::FunctionTemplate#GetFunction()`](https://v8docs.nodesource.com/io.js-3.3/d8/d83/classv8_1_1_function_template.html#a56d904662a86eca78da37d9bb0ed3705) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Function> Nan::GetFunction(v8::Local<v8::FunctionTemplate> t); +``` + + +<a name="api_nan_set"></a> +### Nan::Set() + +A helper method for calling [`v8::Object#Set()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a67604ea3734f170c66026064ea808f20) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key, + v8::Local<v8::Value> value) +Nan::Maybe<bool> Nan::Set(v8::Local<v8::Object> obj, + uint32_t index, + v8::Local<v8::Value> value); +``` + + +<a name="api_nan_define_own_property"></a> +### Nan::DefineOwnProperty() + +A helper method for calling [`v8::Object#DefineOwnProperty()`](https://v8docs.nodesource.com/node-4.8/db/d85/classv8_1_1_object.html#a6f76b2ed605cb8f9185b92de0033a820) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::DefineOwnProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key, + v8::Local<v8::Value> value, + v8::PropertyAttribute attribs = v8::None); +``` + + +<a name="api_nan_force_set"></a> +### <del>Nan::ForceSet()</del> + +Deprecated, use <a href="#api_nan_define_own_property"><code>Nan::DefineOwnProperty()</code></a>. + +<del>A helper method for calling [`v8::Object#ForceSet()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a796b7b682896fb64bf1872747734e836) in a way compatible across supported versions of V8.</del> + +Signature: + +```c++ +NAN_DEPRECATED Nan::Maybe<bool> Nan::ForceSet(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key, + v8::Local<v8::Value> value, + v8::PropertyAttribute attribs = v8::None); +``` + + +<a name="api_nan_get"></a> +### Nan::Get() + +A helper method for calling [`v8::Object#Get()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a2565f03e736694f6b1e1cf22a0b4eac2) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, + v8::Local<v8::Value> key); +Nan::MaybeLocal<v8::Value> Nan::Get(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_get_property_attribute"></a> +### Nan::GetPropertyAttributes() + +A helper method for calling [`v8::Object#GetPropertyAttributes()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a9b898894da3d1db2714fd9325a54fe57) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<v8::PropertyAttribute> Nan::GetPropertyAttributes( + v8::Local<v8::Object> obj, + v8::Local<v8::Value> key); +``` + + +<a name="api_nan_has"></a> +### Nan::Has() + +A helper method for calling [`v8::Object#Has()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab3c3d89ea7c2f9afd08965bd7299a41d) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, v8::Local<v8::String> key); +Nan::Maybe<bool> Nan::Has(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_delete"></a> +### Nan::Delete() + +A helper method for calling [`v8::Object#Delete()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a2fa0f5a592582434ed1ceceff7d891ef) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +Nan::Maybe<bool> Nan::Delete(v8::Local<v8::Object> obj, uint32_t index); +``` + + +<a name="api_nan_get_property_names"></a> +### Nan::GetPropertyNames() + +A helper method for calling [`v8::Object#GetPropertyNames()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#aced885270cfd2c956367b5eedc7fbfe8) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Array> Nan::GetPropertyNames(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_get_own_property_names"></a> +### Nan::GetOwnPropertyNames() + +A helper method for calling [`v8::Object#GetOwnPropertyNames()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a79a6e4d66049b9aa648ed4dfdb23e6eb) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Array> Nan::GetOwnPropertyNames(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_set_prototype"></a> +### Nan::SetPrototype() + +A helper method for calling [`v8::Object#SetPrototype()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a442706b22fceda6e6d1f632122a9a9f4) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::SetPrototype(v8::Local<v8::Object> obj, + v8::Local<v8::Value> prototype); +``` + + +<a name="api_nan_object_proto_to_string"></a> +### Nan::ObjectProtoToString() + +A helper method for calling [`v8::Object#ObjectProtoToString()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab7a92b4dcf822bef72f6c0ac6fea1f0b) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::ObjectProtoToString(v8::Local<v8::Object> obj); +``` + + +<a name="api_nan_has_own_property"></a> +### Nan::HasOwnProperty() + +A helper method for calling [`v8::Object#HasOwnProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab7b7245442ca6de1e1c145ea3fd653ff) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasOwnProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_has_real_named_property"></a> +### Nan::HasRealNamedProperty() + +A helper method for calling [`v8::Object#HasRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ad8b80a59c9eb3c1e6c3cd6c84571f767) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealNamedProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_has_real_indexed_property"></a> +### Nan::HasRealIndexedProperty() + +A helper method for calling [`v8::Object#HasRealIndexedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#af94fc1135a5e74a2193fb72c3a1b9855) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealIndexedProperty(v8::Local<v8::Object> obj, + uint32_t index); +``` + + +<a name="api_nan_has_real_named_callback_property"></a> +### Nan::HasRealNamedCallbackProperty() + +A helper method for calling [`v8::Object#HasRealNamedCallbackProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#af743b7ea132b89f84d34d164d0668811) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasRealNamedCallbackProperty( + v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_get_real_named_property_in_prototype_chain"></a> +### Nan::GetRealNamedPropertyInPrototypeChain() + +A helper method for calling [`v8::Object#GetRealNamedPropertyInPrototypeChain()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a8700b1862e6b4783716964ba4d5e6172) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetRealNamedPropertyInPrototypeChain( + v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_get_real_named_property"></a> +### Nan::GetRealNamedProperty() + +A helper method for calling [`v8::Object#GetRealNamedProperty()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a84471a824576a5994fdd0ffcbf99ccc0) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetRealNamedProperty(v8::Local<v8::Object> obj, + v8::Local<v8::String> key); +``` + + +<a name="api_nan_call_as_function"></a> +### Nan::CallAsFunction() + +A helper method for calling [`v8::Object#CallAsFunction()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a9ef18be634e79b4f0cdffa1667a29f58) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::CallAsFunction(v8::Local<v8::Object> obj, + v8::Local<v8::Object> recv, + int argc, + v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_call_as_constructor"></a> +### Nan::CallAsConstructor() + +A helper method for calling [`v8::Object#CallAsConstructor()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#a50d571de50d0b0dfb28795619d07a01b) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::CallAsConstructor(v8::Local<v8::Object> obj, + int argc, + v8::Local<v8::Value> argv[]); +``` + + +<a name="api_nan_get_source_line"></a> +### Nan::GetSourceLine() + +A helper method for calling [`v8::Message#GetSourceLine()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#a849f7a6c41549d83d8159825efccd23a) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::GetSourceLine(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_line_number"></a> +### Nan::GetLineNumber() + +A helper method for calling [`v8::Message#GetLineNumber()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#adbe46c10a88a6565f2732a2d2adf99b9) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetLineNumber(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_start_column"></a> +### Nan::GetStartColumn() + +A helper method for calling [`v8::Message#GetStartColumn()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#a60ede616ba3822d712e44c7a74487ba6) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetStartColumn(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_get_end_column"></a> +### Nan::GetEndColumn() + +A helper method for calling [`v8::Message#GetEndColumn()`](https://v8docs.nodesource.com/io.js-3.3/d9/d28/classv8_1_1_message.html#aaa004cf19e529da980bc19fcb76d93be) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<int> Nan::GetEndColumn(v8::Local<v8::Message> msg); +``` + + +<a name="api_nan_clone_element_at"></a> +### Nan::CloneElementAt() + +A helper method for calling [`v8::Array#CloneElementAt()`](https://v8docs.nodesource.com/io.js-3.3/d3/d32/classv8_1_1_array.html#a1d3a878d4c1c7cae974dd50a1639245e) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Object> Nan::CloneElementAt(v8::Local<v8::Array> array, uint32_t index); +``` + +<a name="api_nan_has_private"></a> +### Nan::HasPrivate() + +A helper method for calling [`v8::Object#HasPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#af68a0b98066cfdeb8f943e98a40ba08d) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_get_private"></a> +### Nan::GetPrivate() + +A helper method for calling [`v8::Object#GetPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#a169f2da506acbec34deadd9149a1925a) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_set_private"></a> +### Nan::SetPrivate() + +A helper method for calling [`v8::Object#SetPrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#ace1769b0f3b86bfe9fda1010916360ee) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::SetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key, v8::Local<v8::Value> value); +``` + +<a name="api_nan_delete_private"></a> +### Nan::DeletePrivate() + +A helper method for calling [`v8::Object#DeletePrivate()`](https://v8docs.nodesource.com/node-7.2/db/d85/classv8_1_1_object.html#a138bb32a304f3982be02ad499693b8fd) in a way compatible across supported versions of V8. + +Signature: + +```c++ +Nan::Maybe<bool> Nan::DeletePrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key); +``` + +<a name="api_nan_make_maybe"></a> +### Nan::MakeMaybe() + +Wraps a `v8::Local<>` in a `Nan::MaybeLocal<>`. When called with a `Nan::MaybeLocal<>` it just returns its argument. This is useful in generic template code that builds on NAN. + +Synopsis: + +```c++ + MaybeLocal<v8::Number> someNumber = MakeMaybe(New<v8::Number>(3.141592654)); + MaybeLocal<v8::String> someString = MakeMaybe(New<v8::String>("probably")); +``` + +Signature: + +```c++ +template <typename T, template <typename> class MaybeMaybe> +Nan::MaybeLocal<T> Nan::MakeMaybe(MaybeMaybe<T> v); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/methods.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/methods.md new file mode 100644 index 0000000000000000000000000000000000000000..bae46f26f30cac36e52260087c87cb2cd223d72f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/methods.md @@ -0,0 +1,659 @@ +## JavaScript-accessible methods + +A _template_ is a blueprint for JavaScript functions and objects in a context. You can use a template to wrap C++ functions and data structures within JavaScript objects so that they can be manipulated from JavaScript. See the V8 Embedders Guide section on [Templates](https://github.com/v8/v8/wiki/Embedder%27s-Guide#templates) for further information. + +In order to expose functionality to JavaScript via a template, you must provide it to V8 in a form that it understands. Across the versions of V8 supported by NAN, JavaScript-accessible method signatures vary widely, NAN fully abstracts method declaration and provides you with an interface that is similar to the most recent V8 API but is backward-compatible with older versions that still use the now-deceased `v8::Argument` type. + +* **Method argument types** + - <a href="#api_nan_function_callback_info"><b><code>Nan::FunctionCallbackInfo</code></b></a> + - <a href="#api_nan_property_callback_info"><b><code>Nan::PropertyCallbackInfo</code></b></a> + - <a href="#api_nan_return_value"><b><code>Nan::ReturnValue</code></b></a> +* **Method declarations** + - <a href="#api_nan_method"><b>Method declaration</b></a> + - <a href="#api_nan_getter"><b>Getter declaration</b></a> + - <a href="#api_nan_setter"><b>Setter declaration</b></a> + - <a href="#api_nan_property_getter"><b>Property getter declaration</b></a> + - <a href="#api_nan_property_setter"><b>Property setter declaration</b></a> + - <a href="#api_nan_property_enumerator"><b>Property enumerator declaration</b></a> + - <a href="#api_nan_property_deleter"><b>Property deleter declaration</b></a> + - <a href="#api_nan_property_query"><b>Property query declaration</b></a> + - <a href="#api_nan_index_getter"><b>Index getter declaration</b></a> + - <a href="#api_nan_index_setter"><b>Index setter declaration</b></a> + - <a href="#api_nan_index_enumerator"><b>Index enumerator declaration</b></a> + - <a href="#api_nan_index_deleter"><b>Index deleter declaration</b></a> + - <a href="#api_nan_index_query"><b>Index query declaration</b></a> +* Method and template helpers + - <a href="#api_nan_set_method"><b><code>Nan::SetMethod()</code></b></a> + - <a href="#api_nan_set_prototype_method"><b><code>Nan::SetPrototypeMethod()</code></b></a> + - <a href="#api_nan_set_accessor"><b><code>Nan::SetAccessor()</code></b></a> + - <a href="#api_nan_set_named_property_handler"><b><code>Nan::SetNamedPropertyHandler()</code></b></a> + - <a href="#api_nan_set_indexed_property_handler"><b><code>Nan::SetIndexedPropertyHandler()</code></b></a> + - <a href="#api_nan_set_template"><b><code>Nan::SetTemplate()</code></b></a> + - <a href="#api_nan_set_prototype_template"><b><code>Nan::SetPrototypeTemplate()</code></b></a> + - <a href="#api_nan_set_instance_template"><b><code>Nan::SetInstanceTemplate()</code></b></a> + - <a href="#api_nan_set_call_handler"><b><code>Nan::SetCallHandler()</code></b></a> + - <a href="#api_nan_set_call_as_function_handler"><b><code>Nan::SetCallAsFunctionHandler()</code></b></a> + +<a name="api_nan_function_callback_info"></a> +### Nan::FunctionCallbackInfo + +`Nan::FunctionCallbackInfo` should be used in place of [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.0/dd/d0d/classv8_1_1_function_callback_info.html), even with older versions of Node where `v8::FunctionCallbackInfo` does not exist. + +Definition: + +```c++ +template<typename T> class FunctionCallbackInfo { + public: + ReturnValue<T> GetReturnValue() const; + v8::Local<v8::Function> Callee(); + v8::Local<v8::Value> Data(); + v8::Local<v8::Object> Holder(); + bool IsConstructCall(); + int Length() const; + v8::Local<v8::Value> operator[](int i) const; + v8::Local<v8::Object> This() const; + v8::Isolate *GetIsolate() const; +}; +``` + +See the [`v8::FunctionCallbackInfo`](https://v8docs.nodesource.com/node-8.0/dd/d0d/classv8_1_1_function_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from methods. + +<a name="api_nan_property_callback_info"></a> +### Nan::PropertyCallbackInfo + +`Nan::PropertyCallbackInfo` should be used in place of [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.0/d7/dc5/classv8_1_1_property_callback_info.html), even with older versions of Node where `v8::PropertyCallbackInfo` does not exist. + +Definition: + +```c++ +template<typename T> class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> { + public: + ReturnValue<T> GetReturnValue() const; + v8::Isolate* GetIsolate() const; + v8::Local<v8::Value> Data() const; + v8::Local<v8::Object> This() const; + v8::Local<v8::Object> Holder() const; +}; +``` + +See the [`v8::PropertyCallbackInfo`](https://v8docs.nodesource.com/node-8.0/d7/dc5/classv8_1_1_property_callback_info.html) documentation for usage details on these. See [`Nan::ReturnValue`](#api_nan_return_value) for further information on how to set a return value from property accessor methods. + +<a name="api_nan_return_value"></a> +### Nan::ReturnValue + +`Nan::ReturnValue` is used in place of [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.0/da/da7/classv8_1_1_return_value.html) on both [`Nan::FunctionCallbackInfo`](#api_nan_function_callback_info) and [`Nan::PropertyCallbackInfo`](#api_nan_property_callback_info) as the return type of `GetReturnValue()`. + +Example usage: + +```c++ +void EmptyArray(const Nan::FunctionCallbackInfo<v8::Value>& info) { + info.GetReturnValue().Set(Nan::New<v8::Array>()); +} +``` + +Definition: + +```c++ +template<typename T> class ReturnValue { + public: + // Handle setters + template <typename S> void Set(const v8::Local<S> &handle); + template <typename S> void Set(const Nan::Global<S> &handle); + + // Fast primitive setters + void Set(bool value); + void Set(double i); + void Set(int32_t i); + void Set(uint32_t i); + + // Fast JS primitive setters + void SetNull(); + void SetUndefined(); + void SetEmptyString(); + + // Convenience getter for isolate + v8::Isolate *GetIsolate() const; +}; +``` + +See the documentation on [`v8::ReturnValue`](https://v8docs.nodesource.com/node-8.0/da/da7/classv8_1_1_return_value.html) for further information on this. + +<a name="api_nan_method"></a> +### Method declaration + +JavaScript-accessible methods should be declared with the following signature to form a `Nan::FunctionCallback`: + +```c++ +typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void MethodName(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a method as one is implicitly created for you. + +**Example usage** + +```c++ +// .h: +class Foo : public Nan::ObjectWrap { + ... + + static void Bar(const Nan::FunctionCallbackInfo<v8::Value>& info); + static void Baz(const Nan::FunctionCallbackInfo<v8::Value>& info); +} + + +// .cc: +void Foo::Bar(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} + +void Foo::Baz(const Nan::FunctionCallbackInfo<v8::Value>& info) { + ... +} +``` + +A helper macro `NAN_METHOD(methodname)` exists, compatible with NAN v1 method declarations. + +**Example usage with `NAN_METHOD(methodname)`** + +```c++ +// .h: +class Foo : public Nan::ObjectWrap { + ... + + static NAN_METHOD(Bar); + static NAN_METHOD(Baz); +} + + +// .cc: +NAN_METHOD(Foo::Bar) { + ... +} + +NAN_METHOD(Foo::Baz) { + ... +} +``` + +Use [`Nan::SetPrototypeMethod`](#api_nan_set_prototype_method) to attach a method to a JavaScript function prototype or [`Nan::SetMethod`](#api_nan_set_method) to attach a method directly on a JavaScript object. + +<a name="api_nan_getter"></a> +### Getter declaration + +JavaScript-accessible getters should be declared with the following signature to form a `Nan::GetterCallback`: + +```c++ +typedef void(*GetterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void GetterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a getter as one is implicitly created for you. + +A helper macro `NAN_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). + +<a name="api_nan_setter"></a> +### Setter declaration + +JavaScript-accessible setters should be declared with the following signature to form a <b><code>Nan::SetterCallback</code></b>: + +```c++ +typedef void(*SetterCallback)(v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<void>&); +``` + +Example: + +```c++ +void SetterName(v8::Local<v8::String> property, + v8::Local<v8::Value> value, + const Nan::PropertyCallbackInfo<void>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a setter as one is implicitly created for you. + +A helper macro `NAN_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on [Accessors](https://developers.google.com/v8/embed#accesssors). + +<a name="api_nan_property_getter"></a> +### Property getter declaration + +JavaScript-accessible property getters should be declared with the following signature to form a <b><code>Nan::PropertyGetterCallback</code></b>: + +```c++ +typedef void(*PropertyGetterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void PropertyGetterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Value>& info) { + ... +} +``` + +You do not need to declare a new `HandleScope` within a property getter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_setter"></a> +### Property setter declaration + +JavaScript-accessible property setters should be declared with the following signature to form a <b><code>Nan::PropertySetterCallback</code></b>: + +```c++ +typedef void(*PropertySetterCallback)(v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void PropertySetterName(v8::Local<v8::String> property, + v8::Local<v8::Value> value, + const Nan::PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a property setter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_enumerator"></a> +### Property enumerator declaration + +JavaScript-accessible property enumerators should be declared with the following signature to form a <b><code>Nan::PropertyEnumeratorCallback</code></b>: + +```c++ +typedef void(*PropertyEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&); +``` + +Example: + +```c++ +void PropertyEnumeratorName(const Nan::PropertyCallbackInfo<v8::Array>& info); +``` + +You do not need to declare a new `HandleScope` within a property enumerator as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_deleter"></a> +### Property deleter declaration + +JavaScript-accessible property deleters should be declared with the following signature to form a <b><code>Nan::PropertyDeleterCallback</code></b>: + +```c++ +typedef void(*PropertyDeleterCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Boolean>&); +``` + +Example: + +```c++ +void PropertyDeleterName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Boolean>& info); +``` + +You do not need to declare a new `HandleScope` within a property deleter as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_DELETER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_property_query"></a> +### Property query declaration + +JavaScript-accessible property query methods should be declared with the following signature to form a <b><code>Nan::PropertyQueryCallback</code></b>: + +```c++ +typedef void(*PropertyQueryCallback)(v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Integer>&); +``` + +Example: + +```c++ +void PropertyQueryName(v8::Local<v8::String> property, + const Nan::PropertyCallbackInfo<v8::Integer>& info); +``` + +You do not need to declare a new `HandleScope` within a property query method as one is implicitly created for you. + +A helper macro `NAN_PROPERTY_QUERY(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on named property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_getter"></a> +### Index getter declaration + +JavaScript-accessible index getter methods should be declared with the following signature to form a <b><code>Nan::IndexGetterCallback</code></b>: + +```c++ +typedef void(*IndexGetterCallback)(uint32_t, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void IndexGetterName(uint32_t index, const PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a index getter as one is implicitly created for you. + +A helper macro `NAN_INDEX_GETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_setter"></a> +### Index setter declaration + +JavaScript-accessible index setter methods should be declared with the following signature to form a <b><code>Nan::IndexSetterCallback</code></b>: + +```c++ +typedef void(*IndexSetterCallback)(uint32_t, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +``` + +Example: + +```c++ +void IndexSetterName(uint32_t index, + v8::Local<v8::Value> value, + const PropertyCallbackInfo<v8::Value>& info); +``` + +You do not need to declare a new `HandleScope` within a index setter as one is implicitly created for you. + +A helper macro `NAN_INDEX_SETTER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_enumerator"></a> +### Index enumerator declaration + +JavaScript-accessible index enumerator methods should be declared with the following signature to form a <b><code>Nan::IndexEnumeratorCallback</code></b>: + +```c++ +typedef void(*IndexEnumeratorCallback)(const PropertyCallbackInfo<v8::Array>&); +``` + +Example: + +```c++ +void IndexEnumeratorName(const PropertyCallbackInfo<v8::Array>& info); +``` + +You do not need to declare a new `HandleScope` within a index enumerator as one is implicitly created for you. + +A helper macro `NAN_INDEX_ENUMERATOR(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_deleter"></a> +### Index deleter declaration + +JavaScript-accessible index deleter methods should be declared with the following signature to form a <b><code>Nan::IndexDeleterCallback</code></b>: + +```c++ +typedef void(*IndexDeleterCallback)(uint32_t, + const PropertyCallbackInfo<v8::Boolean>&); +``` + +Example: + +```c++ +void IndexDeleterName(uint32_t index, const PropertyCallbackInfo<v8::Boolean>& info); +``` + +You do not need to declare a new `HandleScope` within a index deleter as one is implicitly created for you. + +A helper macro `NAN_INDEX_DELETER(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_index_query"></a> +### Index query declaration + +JavaScript-accessible index query methods should be declared with the following signature to form a <b><code>Nan::IndexQueryCallback</code></b>: + +```c++ +typedef void(*IndexQueryCallback)(uint32_t, + const PropertyCallbackInfo<v8::Integer>&); +``` + +Example: + +```c++ +void IndexQueryName(uint32_t index, const PropertyCallbackInfo<v8::Integer>& info); +``` + +You do not need to declare a new `HandleScope` within a index query method as one is implicitly created for you. + +A helper macro `NAN_INDEX_QUERY(methodname)` exists, compatible with NAN v1 method declarations. + +Also see the V8 Embedders Guide documentation on indexed property [Interceptors](https://developers.google.com/v8/embed#interceptors). + +<a name="api_nan_set_method"></a> +### Nan::SetMethod() + +Sets a method with a given name directly on a JavaScript object where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>). + +Signature: + +```c++ +void Nan::SetMethod(v8::Local<v8::Object> recv, + const char *name, + Nan::FunctionCallback callback) +void Nan::SetMethod(v8::Local<v8::Template> templ, + const char *name, + Nan::FunctionCallback callback) +``` + +<a name="api_nan_set_prototype_method"></a> +### Nan::SetPrototypeMethod() + +Sets a method with a given name on a `FunctionTemplate`'s prototype where the method has the `Nan::FunctionCallback` signature (see <a href="#api_nan_method">Method declaration</a>). + +Signature: + +```c++ +void Nan::SetPrototypeMethod(v8::Local<v8::FunctionTemplate> recv, + const char* name, + Nan::FunctionCallback callback) +``` + +<a name="api_nan_set_accessor"></a> +### Nan::SetAccessor() + +Sets getters and setters for a property with a given name on an `ObjectTemplate` or a plain `Object`. Accepts getters with the `Nan::GetterCallback` signature (see <a href="#api_nan_getter">Getter declaration</a>) and setters with the `Nan::SetterCallback` signature (see <a href="#api_nan_setter">Setter declaration</a>). + +Signature: + +```c++ +void SetAccessor(v8::Local<v8::ObjectTemplate> tpl, + v8::Local<v8::String> name, + Nan::GetterCallback getter, + Nan::SetterCallback setter = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + v8::AccessControl settings = v8::DEFAULT, + v8::PropertyAttribute attribute = v8::None, + imp::Sig signature = imp::Sig()); +bool SetAccessor(v8::Local<v8::Object> obj, + v8::Local<v8::String> name, + Nan::GetterCallback getter, + Nan::SetterCallback setter = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + v8::AccessControl settings = v8::DEFAULT, + v8::PropertyAttribute attribute = v8::None) +``` + +See the V8 [`ObjectTemplate#SetAccessor()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#aca0ed196f8a9adb1f68b1aadb6c9cd77) and [`Object#SetAccessor()`](https://v8docs.nodesource.com/node-8.0/db/d85/classv8_1_1_object.html#a3f9dee085f5ec346465f1dc924325043) for further information about how to use `Nan::SetAccessor()`. + +<a name="api_nan_set_named_property_handler"></a> +### Nan::SetNamedPropertyHandler() + +Sets named property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: + +* Property getters with the `Nan::PropertyGetterCallback` signature (see <a href="#api_nan_property_getter">Property getter declaration</a>) +* Property setters with the `Nan::PropertySetterCallback` signature (see <a href="#api_nan_property_setter">Property setter declaration</a>) +* Property query methods with the `Nan::PropertyQueryCallback` signature (see <a href="#api_nan_property_query">Property query declaration</a>) +* Property deleters with the `Nan::PropertyDeleterCallback` signature (see <a href="#api_nan_property_deleter">Property deleter declaration</a>) +* Property enumerators with the `Nan::PropertyEnumeratorCallback` signature (see <a href="#api_nan_property_enumerator">Property enumerator declaration</a>) + +Signature: + +```c++ +void SetNamedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl, + Nan::PropertyGetterCallback getter, + Nan::PropertySetterCallback setter = 0, + Nan::PropertyQueryCallback query = 0, + Nan::PropertyDeleterCallback deleter = 0, + Nan::PropertyEnumeratorCallback enumerator = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +See the V8 [`ObjectTemplate#SetNamedPropertyHandler()`](https://v8docs.nodesource.com/io.js-3.3/db/d5f/classv8_1_1_object_template.html#a34d1cc45b642cd131706663801aadd76) for further information about how to use `Nan::SetNamedPropertyHandler()`. + +<a name="api_nan_set_indexed_property_handler"></a> +### Nan::SetIndexedPropertyHandler() + +Sets indexed property getters, setters, query, deleter and enumerator methods on an `ObjectTemplate`. Accepts: + +* Indexed property getters with the `Nan::IndexGetterCallback` signature (see <a href="#api_nan_index_getter">Index getter declaration</a>) +* Indexed property setters with the `Nan::IndexSetterCallback` signature (see <a href="#api_nan_index_setter">Index setter declaration</a>) +* Indexed property query methods with the `Nan::IndexQueryCallback` signature (see <a href="#api_nan_index_query">Index query declaration</a>) +* Indexed property deleters with the `Nan::IndexDeleterCallback` signature (see <a href="#api_nan_index_deleter">Index deleter declaration</a>) +* Indexed property enumerators with the `Nan::IndexEnumeratorCallback` signature (see <a href="#api_nan_index_enumerator">Index enumerator declaration</a>) + +Signature: + +```c++ +void SetIndexedPropertyHandler(v8::Local<v8::ObjectTemplate> tpl, + Nan::IndexGetterCallback getter, + Nan::IndexSetterCallback setter = 0, + Nan::IndexQueryCallback query = 0, + Nan::IndexDeleterCallback deleter = 0, + Nan::IndexEnumeratorCallback enumerator = 0, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +See the V8 [`ObjectTemplate#SetIndexedPropertyHandler()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#ac89f06d634add0e890452033f7d17ff1) for further information about how to use `Nan::SetIndexedPropertyHandler()`. + +<a name="api_nan_set_template"></a> +### Nan::SetTemplate() + +Adds properties on an `Object`'s or `Function`'s template. + +Signature: + +```c++ +void Nan::SetTemplate(v8::Local<v8::Template> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetTemplate(v8::Local<v8::Template> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `Template`'s [`Set()`](https://v8docs.nodesource.com/node-8.0/db/df7/classv8_1_1_template.html#ae3fbaff137557aa6a0233bc7e52214ac). + +<a name="api_nan_set_prototype_template"></a> +### Nan::SetPrototypeTemplate() + +Adds properties on an `Object`'s or `Function`'s prototype template. + +Signature: + +```c++ +void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetPrototypeTemplate(v8::Local<v8::FunctionTemplate> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `FunctionTemplate`'s _PrototypeTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.3/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). + +<a name="api_nan_set_instance_template"></a> +### Nan::SetInstanceTemplate() + +Use to add instance properties on `FunctionTemplate`'s. + +Signature: + +```c++ +void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, + const char *name, + v8::Local<v8::Data> value); +void Nan::SetInstanceTemplate(v8::Local<v8::FunctionTemplate> templ, + v8::Local<v8::String> name, + v8::Local<v8::Data> value, + v8::PropertyAttribute attributes) +``` + +Calls the `FunctionTemplate`'s _InstanceTemplate's_ [`Set()`](https://v8docs.nodesource.com/io.js-3.3/db/df7/classv8_1_1_template.html#a2db6a56597bf23c59659c0659e564ddf). + +<a name="api_nan_set_call_handler"></a> +### Nan::SetCallHandler() + +Set the call-handler callback for a `v8::FunctionTemplate`. +This callback is called whenever the function created from this FunctionTemplate is called. + +Signature: + +```c++ +void Nan::SetCallHandler(v8::Local<v8::FunctionTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +Calls the `FunctionTemplate`'s [`SetCallHandler()`](https://v8docs.nodesource.com/node-8.0/d8/d83/classv8_1_1_function_template.html#a2d3845db66392074c5a018a66efbfada). + +<a name="api_nan_set_call_as_function_handler"></a> +### Nan::SetCallAsFunctionHandler() + +Sets the callback to be used when calling instances created from the `v8::ObjectTemplate` as a function. +If no callback is set, instances behave like normal JavaScript objects that cannot be called as a function. + +Signature: + +```c++ +void Nan::SetCallAsFunctionHandler(v8::Local<v8::ObjectTemplate> templ, Nan::FunctionCallback callback, v8::Local<v8::Value> data = v8::Local<v8::Value>()) +``` + +Calls the `ObjectTemplate`'s [`SetCallAsFunctionHandler()`](https://v8docs.nodesource.com/node-8.0/db/d5f/classv8_1_1_object_template.html#a5e9612fc80bf6db8f2da199b9b0bd04e). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/new.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/new.md new file mode 100644 index 0000000000000000000000000000000000000000..0804b62f9ef5e939fd942d82f4d15b20560e8b15 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/new.md @@ -0,0 +1,147 @@ +## New + +NAN provides a `Nan::New()` helper for the creation of new JavaScript objects in a way that's compatible across the supported versions of V8. + + - <a href="#api_nan_new"><b><code>Nan::New()</code></b></a> + - <a href="#api_nan_undefined"><b><code>Nan::Undefined()</code></b></a> + - <a href="#api_nan_null"><b><code>Nan::Null()</code></b></a> + - <a href="#api_nan_true"><b><code>Nan::True()</code></b></a> + - <a href="#api_nan_false"><b><code>Nan::False()</code></b></a> + - <a href="#api_nan_empty_string"><b><code>Nan::EmptyString()</code></b></a> + + +<a name="api_nan_new"></a> +### Nan::New() + +`Nan::New()` should be used to instantiate new JavaScript objects. + +Refer to the specific V8 type in the [V8 documentation](https://v8docs.nodesource.com/io.js-3.3/d1/d83/classv8_1_1_data.html) for information on the types of arguments required for instantiation. + +Signatures: + +Return types are mostly omitted from the signatures for simplicity. In most cases the type will be contained within a `v8::Local<T>`. The following types will be contained within a `Nan::MaybeLocal<T>`: `v8::String`, `v8::Date`, `v8::RegExp`, `v8::Script`, `v8::UnboundScript`. + +Empty objects: + +```c++ +Nan::New<T>(); +``` + +Generic single and multiple-argument: + +```c++ +Nan::New<T>(A0 arg0); +Nan::New<T>(A0 arg0, A1 arg1); +Nan::New<T>(A0 arg0, A1 arg1, A2 arg2); +Nan::New<T>(A0 arg0, A1 arg1, A2 arg2, A3 arg3); +``` + +For creating `v8::FunctionTemplate` and `v8::Function` objects: + +_The definition of `Nan::FunctionCallback` can be found in the [Method declaration](./methods.md#api_nan_method) documentation._ + +```c++ +Nan::New<T>(Nan::FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>()); +Nan::New<T>(Nan::FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>(), + A2 a2 = A2()); +``` + +Native number types: + +```c++ +v8::Local<v8::Boolean> Nan::New<T>(bool value); +v8::Local<v8::Int32> Nan::New<T>(int32_t value); +v8::Local<v8::Uint32> Nan::New<T>(uint32_t value); +v8::Local<v8::Number> Nan::New<T>(double value); +``` + +String types: + +```c++ +Nan::MaybeLocal<v8::String> Nan::New<T>(std::string const& value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value, int length); +Nan::MaybeLocal<v8::String> Nan::New<T>(const char * value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value); +Nan::MaybeLocal<v8::String> Nan::New<T>(const uint16_t * value, int length); +``` + +Specialized types: + +```c++ +v8::Local<v8::String> Nan::New<T>(v8::String::ExternalStringResource * value); +v8::Local<v8::String> Nan::New<T>(Nan::ExternalOneByteStringResource * value); +v8::Local<v8::RegExp> Nan::New<T>(v8::Local<v8::String> pattern, v8::RegExp::Flags flags); +``` + +Note that `Nan::ExternalOneByteStringResource` maps to [`v8::String::ExternalOneByteStringResource`](https://v8docs.nodesource.com/io.js-3.3/d9/db3/classv8_1_1_string_1_1_external_one_byte_string_resource.html), and `v8::String::ExternalAsciiStringResource` in older versions of V8. + + +<a name="api_nan_undefined"></a> +### Nan::Undefined() + +A helper method to reference the `v8::Undefined` object in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Primitive> Nan::Undefined() +``` + +<a name="api_nan_null"></a> +### Nan::Null() + +A helper method to reference the `v8::Null` object in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Primitive> Nan::Null() +``` + +<a name="api_nan_true"></a> +### Nan::True() + +A helper method to reference the `v8::Boolean` object representing the `true` value in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Boolean> Nan::True() +``` + +<a name="api_nan_false"></a> +### Nan::False() + +A helper method to reference the `v8::Boolean` object representing the `false` value in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Boolean> Nan::False() +``` + +<a name="api_nan_empty_string"></a> +### Nan::EmptyString() + +Call [`v8::String::Empty`](https://v8docs.nodesource.com/io.js-3.3/d2/db3/classv8_1_1_string.html#a7c1bc8886115d7ee46f1d571dd6ebc6d) to reference the empty string in a way that is compatible across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::String> Nan::EmptyString() +``` + + +<a name="api_nan_new_one_byte_string"></a> +### Nan::NewOneByteString() + +An implementation of [`v8::String::NewFromOneByte()`](https://v8docs.nodesource.com/io.js-3.3/d2/db3/classv8_1_1_string.html#a5264d50b96d2c896ce525a734dc10f09) provided for consistent availability and API across supported versions of V8. Allocates a new string from Latin-1 data. + +Signature: + +```c++ +Nan::MaybeLocal<v8::String> Nan::NewOneByteString(const uint8_t * value, + int length = -1) +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/node_misc.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/node_misc.md new file mode 100644 index 0000000000000000000000000000000000000000..11a1990a4fb50ffd606abce2b5d8162972fd1e54 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/node_misc.md @@ -0,0 +1,123 @@ +## Miscellaneous Node Helpers + + - <a href="#api_nan_asyncresource"><b><code>Nan::AsyncResource</code></b></a> + - <a href="#api_nan_make_callback"><b><code>Nan::MakeCallback()</code></b></a> + - <a href="#api_nan_module_init"><b><code>NAN_MODULE_INIT()</code></b></a> + - <a href="#api_nan_export"><b><code>Nan::Export()</code></b></a> + +<a name="api_nan_asyncresource"></a> +### Nan::AsyncResource + +This class is analogous to the `AsyncResource` JavaScript class exposed by Node's [async_hooks][] API. + +When calling back into JavaScript asynchornously, special care must be taken to ensure that the runtime can properly track +async hops. `Nan::AsyncResource` is a class that provides an RAII wrapper around `node::EmitAsyncInit`, `node::EmitAsyncDestroy`, +and `node::MakeCallback`. Using this mechanism to call back into JavaScript, as opposed to `Nan::MakeCallback` or +`v8::Function::Call` ensures that the callback is executed in the correct async context. This ensures that async mechanisms +such as domains and [async_hooks][] function correctly. + +Definition: + +```c++ +class AsyncResource { + public: + AsyncResource(v8::Local<v8::String> name, + v8::Local<v8::Object> resource = New<v8::Object>()); + AsyncResource(const char* name, + v8::Local<v8::Object> resource = New<v8::Object>()); + ~AsyncResource(); + + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); + v8::MaybeLocal<v8::Value> runInAsyncScope(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); +}; +``` + +* `name`: Identifier for the kind of resource that is being provided for diagnostics information exposed by the [async_hooks][] + API. This will be passed to the possible `init` hook as the `type`. To avoid name collisions with other modules we recommend + that the name include the name of the owning module as a prefix. For example `mysql` module could use something like + `mysql:batch-db-query-resource`. +* `resource`: An optional object associated with the async work that will be passed to the possible [async_hooks][] + `init` hook. If this parameter is omitted, or an empty handle is provided, this object will be created automatically. +* When calling JS on behalf of this resource, one can use `runInAsyncScope`. This will ensure that the callback runs in the + correct async execution context. +* `AsyncDestroy` is automatically called when an AsyncResource object is destroyed. + +For more details, see the Node [async_hooks][] documentation. You might also want to take a look at the documentation for the +[N-API counterpart][napi]. For example usage, see the `asyncresource.cpp` example in the `test/cpp` directory. + +<a name="api_nan_make_callback"></a> +### Nan::MakeCallback() + +Deprecated wrappers around the legacy `node::MakeCallback()` APIs. Node.js 10+ +has deprecated these legacy APIs as they do not provide a mechanism to preserve +async context. + +We recommend that you use the `AsyncResource` class and `AsyncResource::runInAsyncScope` instead of using `Nan::MakeCallback` or +`v8::Function#Call()` directly. `AsyncResource` properly takes care of running the callback in the correct async execution +context – something that is essential for functionality like domains, async_hooks and async debugging. + +Signatures: + +```c++ +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); +NAN_DEPRECATED +v8::Local<v8::Value> Nan::MakeCallback(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); +``` + + +<a name="api_nan_module_init"></a> +### NAN_MODULE_INIT() + +Used to define the entry point function to a Node add-on. Creates a function with a given `name` that receives a `target` object representing the equivalent of the JavaScript `exports` object. + +See example below. + +<a name="api_nan_export"></a> +### Nan::Export() + +A simple helper to register a `v8::FunctionTemplate` from a JavaScript-accessible method (see [Methods](./methods.md)) as a property on an object. Can be used in a way similar to assigning properties to `module.exports` in JavaScript. + +Signature: + +```c++ +void Export(v8::Local<v8::Object> target, const char *name, Nan::FunctionCallback f) +``` + +Also available as the shortcut `NAN_EXPORT` macro. + +Example: + +```c++ +NAN_METHOD(Foo) { + ... +} + +NAN_MODULE_INIT(Init) { + NAN_EXPORT(target, Foo); +} +``` + +[async_hooks]: https://nodejs.org/dist/latest-v9.x/docs/api/async_hooks.html +[napi]: https://nodejs.org/dist/latest-v9.x/docs/api/n-api.html#n_api_custom_asynchronous_operations diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/object_wrappers.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/object_wrappers.md new file mode 100644 index 0000000000000000000000000000000000000000..e89832b65dd4507071f647458e3272f4c0c65425 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/object_wrappers.md @@ -0,0 +1,263 @@ +## Object Wrappers + +The `ObjectWrap` class can be used to make wrapped C++ objects and a factory of wrapped objects. + + - <a href="#api_nan_object_wrap"><b><code>Nan::ObjectWrap</code></b></a> + + +<a name="api_nan_object_wrap"></a> +### Nan::ObjectWrap() + +A reimplementation of `node::ObjectWrap` that adds some API not present in older versions of Node. Should be preferred over `node::ObjectWrap` in all cases for consistency. + +Definition: + +```c++ +class ObjectWrap { + public: + ObjectWrap(); + + virtual ~ObjectWrap(); + + template <class T> + static inline T* Unwrap(v8::Local<v8::Object> handle); + + inline v8::Local<v8::Object> handle(); + + inline Nan::Persistent<v8::Object>& persistent(); + + protected: + inline void Wrap(v8::Local<v8::Object> handle); + + inline void MakeWeak(); + + /* Ref() marks the object as being attached to an event loop. + * Refed objects will not be garbage collected, even if + * all references are lost. + */ + virtual void Ref(); + + /* Unref() marks an object as detached from the event loop. This is its + * default state. When an object with a "weak" reference changes from + * attached to detached state it will be freed. Be careful not to access + * the object after making this call as it might be gone! + * (A "weak reference" means an object that only has a + * persistant handle.) + * + * DO NOT CALL THIS FROM DESTRUCTOR + */ + virtual void Unref(); + + int refs_; // ro +}; +``` + +See the Node documentation on [Wrapping C++ Objects](https://nodejs.org/api/addons.html#addons_wrapping_c_objects) for more details. + +### This vs. Holder + +When calling `Unwrap`, it is important that the argument is indeed some JavaScript object which got wrapped by a `Wrap` call for this class or any derived class. +The `Signature` installed by [`Nan::SetPrototypeMethod()`](methods.md#api_nan_set_prototype_method) does ensure that `info.Holder()` is just such an instance. +In Node 0.12 and later, `info.This()` will also be of such a type, since otherwise the invocation will get rejected. +However, in Node 0.10 and before it was possible to invoke a method on a JavaScript object which just had the extension type in its prototype chain. +In such a situation, calling `Unwrap` on `info.This()` will likely lead to a failed assertion causing a crash, but could lead to even more serious corruption. + +On the other hand, calling `Unwrap` in an [accessor](methods.md#api_nan_set_accessor) should not use `Holder()` if the accessor is defined on the prototype. +So either define your accessors on the instance template, +or use `This()` after verifying that it is indeed a valid object. + +### Examples + +#### Basic + +```c++ +class MyObject : public Nan::ObjectWrap { + public: + static NAN_MODULE_INIT(Init) { + v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); + tpl->SetClassName(Nan::New("MyObject").ToLocalChecked()); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + Nan::SetPrototypeMethod(tpl, "getHandle", GetHandle); + Nan::SetPrototypeMethod(tpl, "getValue", GetValue); + + constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); + Nan::Set(target, Nan::New("MyObject").ToLocalChecked(), + Nan::GetFunction(tpl).ToLocalChecked()); + } + + private: + explicit MyObject(double value = 0) : value_(value) {} + ~MyObject() {} + + static NAN_METHOD(New) { + if (info.IsConstructCall()) { + double value = info[0]->IsUndefined() ? 0 : Nan::To<double>(info[0]).FromJust(); + MyObject *obj = new MyObject(value); + obj->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } else { + const int argc = 1; + v8::Local<v8::Value> argv[argc] = {info[0]}; + v8::Local<v8::Function> cons = Nan::New(constructor()); + info.GetReturnValue().Set(cons->NewInstance(argc, argv)); + } + } + + static NAN_METHOD(GetHandle) { + MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder()); + info.GetReturnValue().Set(obj->handle()); + } + + static NAN_METHOD(GetValue) { + MyObject* obj = Nan::ObjectWrap::Unwrap<MyObject>(info.Holder()); + info.GetReturnValue().Set(obj->value_); + } + + static inline Nan::Persistent<v8::Function> & constructor() { + static Nan::Persistent<v8::Function> my_constructor; + return my_constructor; + } + + double value_; +}; + +NODE_MODULE(objectwrapper, MyObject::Init) +``` + +To use in Javascript: + +```Javascript +var objectwrapper = require('bindings')('objectwrapper'); + +var obj = new objectwrapper.MyObject(5); +console.log('Should be 5: ' + obj.getValue()); +``` + +#### Factory of wrapped objects + +```c++ +class MyFactoryObject : public Nan::ObjectWrap { + public: + static NAN_MODULE_INIT(Init) { + v8::Local<v8::FunctionTemplate> tpl = Nan::New<v8::FunctionTemplate>(New); + tpl->InstanceTemplate()->SetInternalFieldCount(1); + + Nan::SetPrototypeMethod(tpl, "getValue", GetValue); + + constructor().Reset(Nan::GetFunction(tpl).ToLocalChecked()); + } + + static NAN_METHOD(NewInstance) { + v8::Local<v8::Function> cons = Nan::New(constructor()); + double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0; + const int argc = 1; + v8::Local<v8::Value> argv[1] = {Nan::New(value)}; + info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); + } + + // Needed for the next example: + inline double value() const { + return value_; + } + + private: + explicit MyFactoryObject(double value = 0) : value_(value) {} + ~MyFactoryObject() {} + + static NAN_METHOD(New) { + if (info.IsConstructCall()) { + double value = info[0]->IsNumber() ? Nan::To<double>(info[0]).FromJust() : 0; + MyFactoryObject * obj = new MyFactoryObject(value); + obj->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } else { + const int argc = 1; + v8::Local<v8::Value> argv[argc] = {info[0]}; + v8::Local<v8::Function> cons = Nan::New(constructor()); + info.GetReturnValue().Set(Nan::NewInstance(cons, argc, argv).ToLocalChecked()); + } + } + + static NAN_METHOD(GetValue) { + MyFactoryObject* obj = ObjectWrap::Unwrap<MyFactoryObject>(info.Holder()); + info.GetReturnValue().Set(obj->value_); + } + + static inline Nan::Persistent<v8::Function> & constructor() { + static Nan::Persistent<v8::Function> my_constructor; + return my_constructor; + } + + double value_; +}; + +NAN_MODULE_INIT(Init) { + MyFactoryObject::Init(target); + Nan::Set(target, + Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(), + Nan::GetFunction( + Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked() + ); +} + +NODE_MODULE(wrappedobjectfactory, Init) +``` + +To use in Javascript: + +```Javascript +var wrappedobjectfactory = require('bindings')('wrappedobjectfactory'); + +var obj = wrappedobjectfactory.newFactoryObjectInstance(10); +console.log('Should be 10: ' + obj.getValue()); +``` + +#### Passing wrapped objects around + +Use the `MyFactoryObject` class above along with the following: + +```c++ +static NAN_METHOD(Sum) { + Nan::MaybeLocal<v8::Object> maybe1 = Nan::To<v8::Object>(info[0]); + Nan::MaybeLocal<v8::Object> maybe2 = Nan::To<v8::Object>(info[1]); + + // Quick check: + if (maybe1.IsEmpty() || maybe2.IsEmpty()) { + // return value is undefined by default + return; + } + + MyFactoryObject* obj1 = + Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe1.ToLocalChecked()); + MyFactoryObject* obj2 = + Nan::ObjectWrap::Unwrap<MyFactoryObject>(maybe2.ToLocalChecked()); + + info.GetReturnValue().Set(Nan::New<v8::Number>(obj1->value() + obj2->value())); +} + +NAN_MODULE_INIT(Init) { + MyFactoryObject::Init(target); + Nan::Set(target, + Nan::New<v8::String>("newFactoryObjectInstance").ToLocalChecked(), + Nan::GetFunction( + Nan::New<v8::FunctionTemplate>(MyFactoryObject::NewInstance)).ToLocalChecked() + ); + Nan::Set(target, + Nan::New<v8::String>("sum").ToLocalChecked(), + Nan::GetFunction(Nan::New<v8::FunctionTemplate>(Sum)).ToLocalChecked() + ); +} + +NODE_MODULE(myaddon, Init) +``` + +To use in Javascript: + +```Javascript +var myaddon = require('bindings')('myaddon'); + +var obj1 = myaddon.newFactoryObjectInstance(5); +var obj2 = myaddon.newFactoryObjectInstance(10); +console.log('sum of object values: ' + myaddon.sum(obj1, obj2)); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/persistent.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/persistent.md new file mode 100644 index 0000000000000000000000000000000000000000..f6ebefa0b991b549efcf7ff39cd932d4b30c05ab --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/persistent.md @@ -0,0 +1,295 @@ +## Persistent references + +An object reference that is independent of any `HandleScope` is a _persistent_ reference. Where a `Local` handle only lives as long as the `HandleScope` in which it was allocated, a `Persistent` handle remains valid until it is explicitly disposed. + +Due to the evolution of the V8 API, it is necessary for NAN to provide a wrapper implementation of the `Persistent` classes to supply compatibility across the V8 versions supported. + + - <a href="#api_nan_persistent_base"><b><code>Nan::PersistentBase & v8::PersistentBase</code></b></a> + - <a href="#api_nan_non_copyable_persistent_traits"><b><code>Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits</code></b></a> + - <a href="#api_nan_copyable_persistent_traits"><b><code>Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits</code></b></a> + - <a href="#api_nan_persistent"><b><code>Nan::Persistent</code></b></a> + - <a href="#api_nan_global"><b><code>Nan::Global</code></b></a> + - <a href="#api_nan_weak_callback_info"><b><code>Nan::WeakCallbackInfo</code></b></a> + - <a href="#api_nan_weak_callback_type"><b><code>Nan::WeakCallbackType</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://developers.google.com/v8/embed#handles). + +<a name="api_nan_persistent_base"></a> +### Nan::PersistentBase & v8::PersistentBase + +A persistent handle contains a reference to a storage cell in V8 which holds an object value and which is updated by the garbage collector whenever the object is moved. A new storage cell can be created using the constructor or `Nan::PersistentBase::Reset()`. Existing handles can be disposed using an argument-less `Nan::PersistentBase::Reset()`. + +Definition: + +_(note: this is implemented as `Nan::PersistentBase` for older versions of V8 and the native `v8::PersistentBase` is used for newer versions of V8)_ + +```c++ +template<typename T> class PersistentBase { + public: + /** + * If non-empty, destroy the underlying storage cell + */ + void Reset(); + + /** + * If non-empty, destroy the underlying storage cell and create a new one with + * the contents of another if it is also non-empty + */ + template<typename S> void Reset(const v8::Local<S> &other); + + /** + * If non-empty, destroy the underlying storage cell and create a new one with + * the contents of another if it is also non-empty + */ + template<typename S> void Reset(const PersistentBase<S> &other); + + /** + * If non-empty, destroy the underlying storage cell + * IsEmpty() will return true after this call. + */ + bool IsEmpty(); + + void Empty(); + + template<typename S> bool operator==(const PersistentBase<S> &that); + + template<typename S> bool operator==(const v8::Local<S> &that); + + template<typename S> bool operator!=(const PersistentBase<S> &that); + + template<typename S> bool operator!=(const v8::Local<S> &that); + + /** + * Install a finalization callback on this object. + * NOTE: There is no guarantee as to *when* or even *if* the callback is + * invoked. The invocation is performed solely on a best effort basis. + * As always, GC-based finalization should *not* be relied upon for any + * critical form of resource management! At the moment you can either + * specify a parameter for the callback or the location of two internal + * fields in the dying object. + */ + template<typename P> + void SetWeak(P *parameter, + typename WeakCallbackInfo<P>::Callback callback, + WeakCallbackType type); + + void ClearWeak(); + + /** + * Marks the reference to this object independent. Garbage collector is free + * to ignore any object groups containing this object. Weak callback for an + * independent handle should not assume that it will be preceded by a global + * GC prologue callback or followed by a global GC epilogue callback. + */ + void MarkIndependent() const; + + bool IsIndependent() const; + + /** Checks if the handle holds the only reference to an object. */ + bool IsNearDeath() const; + + /** Returns true if the handle's reference is weak. */ + bool IsWeak() const +}; +``` + +See the V8 documentation for [`PersistentBase`](https://v8docs.nodesource.com/io.js-3.3/d4/dca/classv8_1_1_persistent_base.html) for further information. + +**Tip:** To get a `v8::Local` reference to the original object back from a `PersistentBase` or `Persistent` object: + +```c++ +v8::Local<v8::Object> object = Nan::New(persistent); +``` + +<a name="api_nan_non_copyable_persistent_traits"></a> +### Nan::NonCopyablePersistentTraits & v8::NonCopyablePersistentTraits + +Default traits for `Nan::Persistent`. This class does not allow use of the a copy constructor or assignment operator. At present `kResetInDestructor` is not set, but that will change in a future version. + +Definition: + +_(note: this is implemented as `Nan::NonCopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ + +```c++ +template<typename T> class NonCopyablePersistentTraits { + public: + typedef Persistent<T, NonCopyablePersistentTraits<T> > NonCopyablePersistent; + + static const bool kResetInDestructor = false; + + template<typename S, typename M> + static void Copy(const Persistent<S, M> &source, + NonCopyablePersistent *dest); + + template<typename O> static void Uncompilable(); +}; +``` + +See the V8 documentation for [`NonCopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.3/de/d73/classv8_1_1_non_copyable_persistent_traits.html) for further information. + +<a name="api_nan_copyable_persistent_traits"></a> +### Nan::CopyablePersistentTraits & v8::CopyablePersistentTraits + +A helper class of traits to allow copying and assignment of `Persistent`. This will clone the contents of storage cell, but not any of the flags, etc.. + +Definition: + +_(note: this is implemented as `Nan::CopyablePersistentTraits` for older versions of V8 and the native `v8::NonCopyablePersistentTraits` is used for newer versions of V8)_ + +```c++ +template<typename T> +class CopyablePersistentTraits { + public: + typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent; + + static const bool kResetInDestructor = true; + + template<typename S, typename M> + static void Copy(const Persistent<S, M> &source, + CopyablePersistent *dest); +}; +``` + +See the V8 documentation for [`CopyablePersistentTraits`](https://v8docs.nodesource.com/io.js-3.3/da/d5c/structv8_1_1_copyable_persistent_traits.html) for further information. + +<a name="api_nan_persistent"></a> +### Nan::Persistent + +A type of `PersistentBase` which allows copy and assignment. Copy, assignment and destructor behavior is controlled by the traits class `M`. + +Definition: + +```c++ +template<typename T, typename M = NonCopyablePersistentTraits<T> > +class Persistent; + +template<typename T, typename M> class Persistent : public PersistentBase<T> { + public: + /** + * A Persistent with no storage cell. + */ + Persistent(); + + /** + * Construct a Persistent from a v8::Local. When the v8::Local is non-empty, a + * new storage cell is created pointing to the same object, and no flags are + * set. + */ + template<typename S> Persistent(v8::Local<S> that); + + /** + * Construct a Persistent from a Persistent. When the Persistent is non-empty, + * a new storage cell is created pointing to the same object, and no flags are + * set. + */ + Persistent(const Persistent &that); + + /** + * The copy constructors and assignment operator create a Persistent exactly + * as the Persistent constructor, but the Copy function from the traits class + * is called, allowing the setting of flags based on the copied Persistent. + */ + Persistent &operator=(const Persistent &that); + + template <typename S, typename M2> + Persistent &operator=(const Persistent<S, M2> &that); + + /** + * The destructor will dispose the Persistent based on the kResetInDestructor + * flags in the traits class. Since not calling dispose can result in a + * memory leak, it is recommended to always set this flag. + */ + ~Persistent(); +}; +``` + +See the V8 documentation for [`Persistent`](https://v8docs.nodesource.com/io.js-3.3/d2/d78/classv8_1_1_persistent.html) for further information. + +<a name="api_nan_global"></a> +### Nan::Global + +A type of `PersistentBase` which has move semantics. + +```c++ +template<typename T> class Global : public PersistentBase<T> { + public: + /** + * A Global with no storage cell. + */ + Global(); + + /** + * Construct a Global from a v8::Local. When the v8::Local is non-empty, a new + * storage cell is created pointing to the same object, and no flags are set. + */ + template<typename S> Global(v8::Local<S> that); + /** + * Construct a Global from a PersistentBase. When the Persistent is non-empty, + * a new storage cell is created pointing to the same object, and no flags are + * set. + */ + template<typename S> Global(const PersistentBase<S> &that); + + /** + * Pass allows returning globals from functions, etc. + */ + Global Pass(); +}; +``` + +See the V8 documentation for [`Global`](https://v8docs.nodesource.com/io.js-3.3/d5/d40/classv8_1_1_global.html) for further information. + +<a name="api_nan_weak_callback_info"></a> +### Nan::WeakCallbackInfo + +`Nan::WeakCallbackInfo` is used as an argument when setting a persistent reference as weak. You may need to free any external resources attached to the object. It is a mirror of `v8:WeakCallbackInfo` as found in newer versions of V8. + +Definition: + +```c++ +template<typename T> class WeakCallbackInfo { + public: + typedef void (*Callback)(const WeakCallbackInfo<T>& data); + + v8::Isolate *GetIsolate() const; + + /** + * Get the parameter that was associated with the weak handle. + */ + T *GetParameter() const; + + /** + * Get pointer from internal field, index can be 0 or 1. + */ + void *GetInternalField(int index) const; +}; +``` + +Example usage: + +```c++ +void weakCallback(const WeakCallbackInfo<int> &data) { + int *parameter = data.GetParameter(); + delete parameter; +} + +Persistent<v8::Object> obj; +int *data = new int(0); +obj.SetWeak(data, callback, WeakCallbackType::kParameter); +``` + +See the V8 documentation for [`WeakCallbackInfo`](https://v8docs.nodesource.com/io.js-3.3/d8/d06/classv8_1_1_weak_callback_info.html) for further information. + +<a name="api_nan_weak_callback_type"></a> +### Nan::WeakCallbackType + +Represents the type of a weak callback. +A weak callback of type `kParameter` makes the supplied parameter to `Nan::PersistentBase::SetWeak` available through `WeakCallbackInfo::GetParameter`. +A weak callback of type `kInternalFields` uses up to two internal fields at indices 0 and 1 on the `Nan::PersistentBase<v8::Object>` being made weak. +Note that only `v8::Object`s and derivatives can have internal fields. + +Definition: + +```c++ +enum class WeakCallbackType { kParameter, kInternalFields }; +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/scopes.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/scopes.md new file mode 100644 index 0000000000000000000000000000000000000000..1dfb417c6097d059380750b22c2219b9cd497dc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/scopes.md @@ -0,0 +1,73 @@ +## Scopes + +A _local handle_ is a pointer to an object. All V8 objects are accessed using handles, they are necessary because of the way the V8 garbage collector works. + +A handle scope can be thought of as a container for any number of handles. When you've finished with your handles, instead of deleting each one individually you can simply delete their scope. + +The creation of `HandleScope` objects is different across the supported versions of V8. Therefore, NAN provides its own implementations that can be used safely across these. + + - <a href="#api_nan_handle_scope"><b><code>Nan::HandleScope</code></b></a> + - <a href="#api_nan_escapable_handle_scope"><b><code>Nan::EscapableHandleScope</code></b></a> + +Also see the V8 Embedders Guide section on [Handles and Garbage Collection](https://github.com/v8/v8/wiki/Embedder%27s%20Guide#handles-and-garbage-collection). + +<a name="api_nan_handle_scope"></a> +### Nan::HandleScope + +A simple wrapper around [`v8::HandleScope`](https://v8docs.nodesource.com/io.js-3.3/d3/d95/classv8_1_1_handle_scope.html). + +Definition: + +```c++ +class Nan::HandleScope { + public: + Nan::HandleScope(); + static int NumberOfHandles(); +}; +``` + +Allocate a new `Nan::HandleScope` whenever you are creating new V8 JavaScript objects. Note that an implicit `HandleScope` is created for you on JavaScript-accessible methods so you do not need to insert one yourself. + +Example: + +```c++ +// new object is created, it needs a new scope: +void Pointless() { + Nan::HandleScope scope; + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); +} + +// JavaScript-accessible method already has a HandleScope +NAN_METHOD(Pointless2) { + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); +} +``` + +<a name="api_nan_escapable_handle_scope"></a> +### Nan::EscapableHandleScope + +Similar to [`Nan::HandleScope`](#api_nan_handle_scope) but should be used in cases where a function needs to return a V8 JavaScript type that has been created within it. + +Definition: + +```c++ +class Nan::EscapableHandleScope { + public: + Nan::EscapableHandleScope(); + static int NumberOfHandles(); + template<typename T> v8::Local<T> Escape(v8::Local<T> value); +} +``` + +Use `Escape(value)` to return the object. + +Example: + +```c++ +v8::Local<v8::Object> EmptyObj() { + Nan::EscapableHandleScope scope; + v8::Local<v8::Object> obj = Nan::New<v8::Object>(); + return scope.Escape(obj); +} +``` + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/script.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/script.md new file mode 100644 index 0000000000000000000000000000000000000000..e518505ec2b82ad7b4d9f92d7271f70c47067cc3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/script.md @@ -0,0 +1,38 @@ +## Script + +NAN provides a `v8::Script` helpers as the API has changed over the supported versions of V8. + + - <a href="#api_nan_compile_script"><b><code>Nan::CompileScript()</code></b></a> + - <a href="#api_nan_run_script"><b><code>Nan::RunScript()</code></b></a> + + +<a name="api_nan_compile_script"></a> +### Nan::CompileScript() + +A wrapper around [`v8::Script::Compile()`](https://v8docs.nodesource.com/io.js-3.3/da/da5/classv8_1_1_script_compiler.html#a93f5072a0db55d881b969e9fc98e564b). + +Note that `Nan::BoundScript` is an alias for `v8::Script`. + +Signature: + +```c++ +Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript( + v8::Local<v8::String> s, + const v8::ScriptOrigin& origin); +Nan::MaybeLocal<Nan::BoundScript> Nan::CompileScript(v8::Local<v8::String> s); +``` + + +<a name="api_nan_run_script"></a> +### Nan::RunScript() + +Calls `script->Run()` or `script->BindToCurrentContext()->Run(Nan::GetCurrentContext())`. + +Note that `Nan::BoundScript` is an alias for `v8::Script` and `Nan::UnboundScript` is an alias for `v8::UnboundScript` where available and `v8::Script` on older versions of V8. + +Signature: + +```c++ +Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::UnboundScript> script) +Nan::MaybeLocal<v8::Value> Nan::RunScript(v8::Local<Nan::BoundScript> script) +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/string_bytes.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/string_bytes.md new file mode 100644 index 0000000000000000000000000000000000000000..7c1bd3250476b6b16a29ff684a3a7f86de26a7f9 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/string_bytes.md @@ -0,0 +1,62 @@ +## Strings & Bytes + +Miscellaneous string & byte encoding and decoding functionality provided for compatibility across supported versions of V8 and Node. Implemented by NAN to ensure that all encoding types are supported, even for older versions of Node where they are missing. + + - <a href="#api_nan_encoding"><b><code>Nan::Encoding</code></b></a> + - <a href="#api_nan_encode"><b><code>Nan::Encode()</code></b></a> + - <a href="#api_nan_decode_bytes"><b><code>Nan::DecodeBytes()</code></b></a> + - <a href="#api_nan_decode_write"><b><code>Nan::DecodeWrite()</code></b></a> + + +<a name="api_nan_encoding"></a> +### Nan::Encoding + +An enum representing the supported encoding types. A copy of `node::encoding` that is consistent across versions of Node. + +Definition: + +```c++ +enum Nan::Encoding { ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER } +``` + + +<a name="api_nan_encode"></a> +### Nan::Encode() + +A wrapper around `node::Encode()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +v8::Local<v8::Value> Nan::Encode(const void *buf, + size_t len, + enum Nan::Encoding encoding = BINARY); +``` + + +<a name="api_nan_decode_bytes"></a> +### Nan::DecodeBytes() + +A wrapper around `node::DecodeBytes()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +ssize_t Nan::DecodeBytes(v8::Local<v8::Value> val, + enum Nan::Encoding encoding = BINARY); +``` + + +<a name="api_nan_decode_write"></a> +### Nan::DecodeWrite() + +A wrapper around `node::DecodeWrite()` that provides a consistent implementation across supported versions of Node. + +Signature: + +```c++ +ssize_t Nan::DecodeWrite(char *buf, + size_t len, + v8::Local<v8::Value> val, + enum Nan::Encoding encoding = BINARY); +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_internals.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_internals.md new file mode 100644 index 0000000000000000000000000000000000000000..430c4353ffc18dd32fd859f362aeff047a2fd745 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_internals.md @@ -0,0 +1,199 @@ +## V8 internals + +The hooks to access V8 internals—including GC and statistics—are different across the supported versions of V8, therefore NAN provides its own hooks that call the appropriate V8 methods. + + - <a href="#api_nan_gc_callback"><b><code>NAN_GC_CALLBACK()</code></b></a> + - <a href="#api_nan_add_gc_epilogue_callback"><b><code>Nan::AddGCEpilogueCallback()</code></b></a> + - <a href="#api_nan_remove_gc_epilogue_callback"><b><code>Nan::RemoveGCEpilogueCallback()</code></b></a> + - <a href="#api_nan_add_gc_prologue_callback"><b><code>Nan::AddGCPrologueCallback()</code></b></a> + - <a href="#api_nan_remove_gc_prologue_callback"><b><code>Nan::RemoveGCPrologueCallback()</code></b></a> + - <a href="#api_nan_get_heap_statistics"><b><code>Nan::GetHeapStatistics()</code></b></a> + - <a href="#api_nan_set_counter_function"><b><code>Nan::SetCounterFunction()</code></b></a> + - <a href="#api_nan_set_create_histogram_function"><b><code>Nan::SetCreateHistogramFunction()</code></b></a> + - <a href="#api_nan_set_add_histogram_sample_function"><b><code>Nan::SetAddHistogramSampleFunction()</code></b></a> + - <a href="#api_nan_idle_notification"><b><code>Nan::IdleNotification()</code></b></a> + - <a href="#api_nan_low_memory_notification"><b><code>Nan::LowMemoryNotification()</code></b></a> + - <a href="#api_nan_context_disposed_notification"><b><code>Nan::ContextDisposedNotification()</code></b></a> + - <a href="#api_nan_get_internal_field_pointer"><b><code>Nan::GetInternalFieldPointer()</code></b></a> + - <a href="#api_nan_set_internal_field_pointer"><b><code>Nan::SetInternalFieldPointer()</code></b></a> + - <a href="#api_nan_adjust_external_memory"><b><code>Nan::AdjustExternalMemory()</code></b></a> + + +<a name="api_nan_gc_callback"></a> +### NAN_GC_CALLBACK(callbackname) + +Use `NAN_GC_CALLBACK` to declare your callbacks for `Nan::AddGCPrologueCallback()` and `Nan::AddGCEpilogueCallback()`. Your new method receives the arguments `v8::GCType type` and `v8::GCCallbackFlags flags`. + +```c++ +static Nan::Persistent<Function> callback; + +NAN_GC_CALLBACK(gcPrologueCallback) { + v8::Local<Value> argv[] = { Nan::New("prologue").ToLocalChecked() }; + Nan::MakeCallback(Nan::GetCurrentContext()->Global(), Nan::New(callback), 1, argv); +} + +NAN_METHOD(Hook) { + callback.Reset(To<Function>(args[0]).ToLocalChecked()); + Nan::AddGCPrologueCallback(gcPrologueCallback); + info.GetReturnValue().Set(info.Holder()); +} +``` + +<a name="api_nan_add_gc_epilogue_callback"></a> +### Nan::AddGCEpilogueCallback() + +Signature: + +```c++ +void Nan::AddGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback, v8::GCType gc_type_filter = v8::kGCTypeAll) +``` + +Calls V8's [`AddGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a90d1860babc76059c62514b422f56960). + +<a name="api_nan_remove_gc_epilogue_callback"></a> +### Nan::RemoveGCEpilogueCallback() + +Signature: + +```c++ +void Nan::RemoveGCEpilogueCallback(v8::Isolate::GCEpilogueCallback callback) +``` + +Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a05c60859fd4b8e96bfcd451281ed6c7c). + +<a name="api_nan_add_gc_prologue_callback"></a> +### Nan::AddGCPrologueCallback() + +Signature: + +```c++ +void Nan::AddGCPrologueCallback(v8::Isolate::GCPrologueCallback, v8::GCType gc_type_filter callback) +``` + +Calls V8's [`AddGCPrologueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ab4b87b8f9f8e5bf95eba4009357e001f). + +<a name="api_nan_remove_gc_prologue_callback"></a> +### Nan::RemoveGCPrologueCallback() + +Signature: + +```c++ +void Nan::RemoveGCPrologueCallback(v8::Isolate::GCPrologueCallback callback) +``` + +Calls V8's [`RemoveGCEpilogueCallback()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a9f6c51932811593f81ff30b949124186). + +<a name="api_nan_get_heap_statistics"></a> +### Nan::GetHeapStatistics() + +Signature: + +```c++ +void Nan::GetHeapStatistics(v8::HeapStatistics *heap_statistics) +``` + +Calls V8's [`GetHeapStatistics()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a5593ac74687b713095c38987e5950b34). + +<a name="api_nan_set_counter_function"></a> +### Nan::SetCounterFunction() + +Signature: + +```c++ +void Nan::SetCounterFunction(v8::CounterLookupCallback cb) +``` + +Calls V8's [`SetCounterFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a045d7754e62fa0ec72ae6c259b29af94). + +<a name="api_nan_set_create_histogram_function"></a> +### Nan::SetCreateHistogramFunction() + +Signature: + +```c++ +void Nan::SetCreateHistogramFunction(v8::CreateHistogramCallback cb) +``` + +Calls V8's [`SetCreateHistogramFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a542d67e85089cb3f92aadf032f99e732). + +<a name="api_nan_set_add_histogram_sample_function"></a> +### Nan::SetAddHistogramSampleFunction() + +Signature: + +```c++ +void Nan::SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) +``` + +Calls V8's [`SetAddHistogramSampleFunction()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#aeb420b690bc2c216882d6fdd00ddd3ea). + +<a name="api_nan_idle_notification"></a> +### Nan::IdleNotification() + +Signature: + +```c++ +void Nan::IdleNotification(v8::HeapStatistics *heap_statistics) +``` + +Calls V8's [`IdleNotification()` or `IdleNotificationDeadline()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad6a2a02657f5425ad460060652a5a118) depending on V8 version. + +<a name="api_nan_low_memory_notification"></a> +### Nan::LowMemoryNotification() + +Signature: + +```c++ +void Nan::LowMemoryNotification() +``` + +Calls V8's [`LowMemoryNotification()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a24647f61d6b41f69668094bdcd6ea91f). + +<a name="api_nan_context_disposed_notification"></a> +### Nan::ContextDisposedNotification() + +Signature: + +```c++ +void Nan::ContextDisposedNotification() +``` + +Calls V8's [`ContextDisposedNotification()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b). + +<a name="api_nan_get_internal_field_pointer"></a> +### Nan::GetInternalFieldPointer() + +Gets a pointer to the internal field with at `index` from a V8 `Object` handle. + +Signature: + +```c++ +void* Nan::GetInternalFieldPointer(v8::Local<v8::Object> object, int index) +``` + +Calls the Object's [`GetAlignedPointerFromInternalField()` or `GetPointerFromInternalField()`](https://v8docs.nodesource.com/io.js-3.3/db/d85/classv8_1_1_object.html#ab3c57184263cf29963ef0017bec82281) depending on the version of V8. + +<a name="api_nan_set_internal_field_pointer"></a> +### Nan::SetInternalFieldPointer() + +Sets the value of the internal field at `index` on a V8 `Object` handle. + +Signature: + +```c++ +void Nan::SetInternalFieldPointer(v8::Local<v8::Object> object, int index, void* value) +``` + +Calls the Object's [`SetAlignedPointerInInternalField()` or `SetPointerInInternalField()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ad7f5dc559866343fe6cd8db1f134d48b) depending on the version of V8. + +<a name="api_nan_adjust_external_memory"></a> +### Nan::AdjustExternalMemory() + +Signature: + +```c++ +int Nan::AdjustExternalMemory(int bytesChange) +``` + +Calls V8's [`AdjustAmountOfExternalAllocatedMemory()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#ae1a59cac60409d3922582c4af675473e). + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_misc.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_misc.md new file mode 100644 index 0000000000000000000000000000000000000000..8aa6653f271f06417d7ad785109ca79faa58f3d4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/doc/v8_misc.md @@ -0,0 +1,85 @@ +## Miscellaneous V8 Helpers + + - <a href="#api_nan_utf8_string"><b><code>Nan::Utf8String</code></b></a> + - <a href="#api_nan_get_current_context"><b><code>Nan::GetCurrentContext()</code></b></a> + - <a href="#api_nan_set_isolate_data"><b><code>Nan::SetIsolateData()</code></b></a> + - <a href="#api_nan_get_isolate_data"><b><code>Nan::GetIsolateData()</code></b></a> + - <a href="#api_nan_typedarray_contents"><b><code>Nan::TypedArrayContents</code></b></a> + + +<a name="api_nan_utf8_string"></a> +### Nan::Utf8String + +Converts an object to a UTF-8-encoded character array. If conversion to a string fails (e.g. due to an exception in the toString() method of the object) then the length() method returns 0 and the * operator returns NULL. The underlying memory used for this object is managed by the object. + +An implementation of [`v8::String::Utf8Value`](https://v8docs.nodesource.com/io.js-3.3/d4/d1b/classv8_1_1_string_1_1_utf8_value.html) that is consistent across all supported versions of V8. + +Definition: + +```c++ +class Nan::Utf8String { + public: + Nan::Utf8String(v8::Local<v8::Value> from); + + int length() const; + + char* operator*(); + const char* operator*() const; +}; +``` + +<a name="api_nan_get_current_context"></a> +### Nan::GetCurrentContext() + +A call to [`v8::Isolate::GetCurrent()->GetCurrentContext()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a81c7a1ed7001ae2a65e89107f75fd053) that works across all supported versions of V8. + +Signature: + +```c++ +v8::Local<v8::Context> Nan::GetCurrentContext() +``` + +<a name="api_nan_set_isolate_data"></a> +### Nan::SetIsolateData() + +A helper to provide a consistent API to [`v8::Isolate#SetData()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#a7acadfe7965997e9c386a05f098fbe36). + +Signature: + +```c++ +void Nan::SetIsolateData(v8::Isolate *isolate, T *data) +``` + + +<a name="api_nan_get_isolate_data"></a> +### Nan::GetIsolateData() + +A helper to provide a consistent API to [`v8::Isolate#GetData()`](https://v8docs.nodesource.com/io.js-3.3/d5/dda/classv8_1_1_isolate.html#aabd223436bc1100a787dadaa024c6257). + +Signature: + +```c++ +T *Nan::GetIsolateData(v8::Isolate *isolate) +``` + +<a name="api_nan_typedarray_contents"></a> +### Nan::TypedArrayContents<T> + +A helper class for accessing the contents of an ArrayBufferView (aka a typedarray) from C++. If the input array is not a valid typedarray, then the data pointer of TypedArrayContents will default to `NULL` and the length will be 0. If the data pointer is not compatible with the alignment requirements of type, an assertion error will fail. + +Note that you must store a reference to the `array` object while you are accessing its contents. + +Definition: + +```c++ +template<typename T> +class Nan::TypedArrayContents { + public: + TypedArrayContents(v8::Local<Value> array); + + size_t length() const; + + T* const operator*(); + const T* const operator*() const; +}; +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/include_dirs.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/include_dirs.js new file mode 100644 index 0000000000000000000000000000000000000000..4f1dfb41667b9b86b4db9bb2255eaef5ab1b9ab6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/include_dirs.js @@ -0,0 +1 @@ +console.log(require('path').relative('.', __dirname)); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan.h new file mode 100644 index 0000000000000000000000000000000000000000..29f084e7695467fda8f1d60f65c476f5fdb8adec --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan.h @@ -0,0 +1,2761 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors: + * - Rod Vagg <https://github.com/rvagg> + * - Benjamin Byholm <https://github.com/kkoopa> + * - Trevor Norris <https://github.com/trevnorris> + * - Nathan Rajlich <https://github.com/TooTallNate> + * - Brett Lawson <https://github.com/brett19> + * - Ben Noordhuis <https://github.com/bnoordhuis> + * - David Siegel <https://github.com/agnat> + * - Michael Ira Krufky <https://github.com/mkrufky> + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + * + * Version 2.10.0: current Node 9.8.0, Node 12: 0.12.18, Node 10: 0.10.48, iojs: 3.3.1 + * + * See https://github.com/nodejs/nan for the latest update to this file + **********************************************************************************/ + +#ifndef NAN_H_ +#define NAN_H_ + +#include <node_version.h> + +#define NODE_0_10_MODULE_VERSION 11 +#define NODE_0_12_MODULE_VERSION 14 +#define ATOM_0_21_MODULE_VERSION 41 +#define IOJS_1_0_MODULE_VERSION 42 +#define IOJS_1_1_MODULE_VERSION 43 +#define IOJS_2_0_MODULE_VERSION 44 +#define IOJS_3_0_MODULE_VERSION 45 +#define NODE_4_0_MODULE_VERSION 46 +#define NODE_5_0_MODULE_VERSION 47 +#define NODE_6_0_MODULE_VERSION 48 +#define NODE_7_0_MODULE_VERSION 51 +#define NODE_8_0_MODULE_VERSION 57 +#define NODE_9_0_MODULE_VERSION 59 + +#ifdef _MSC_VER +# define NAN_HAS_CPLUSPLUS_11 (_MSC_VER >= 1800) +#else +# define NAN_HAS_CPLUSPLUS_11 (__cplusplus >= 201103L) +#endif + +#if NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION && !NAN_HAS_CPLUSPLUS_11 +# error This version of node/NAN/v8 requires a C++11 compiler +#endif + +#include <uv.h> +#include <node.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <algorithm> +#include <cstring> +#include <climits> +#include <cstdlib> +#include <utility> +#if defined(_MSC_VER) +# pragma warning( push ) +# pragma warning( disable : 4530 ) +# include <queue> +# include <string> +# include <vector> +# pragma warning( pop ) +#else +# include <queue> +# include <string> +# include <vector> +#endif + +// uv helpers +#ifdef UV_VERSION_MAJOR +# ifndef UV_VERSION_PATCH +# define UV_VERSION_PATCH 0 +# endif +# define NAUV_UVVERSION ((UV_VERSION_MAJOR << 16) | \ + (UV_VERSION_MINOR << 8) | \ + (UV_VERSION_PATCH)) +#else +# define NAUV_UVVERSION 0x000b00 +#endif + +#if NAUV_UVVERSION < 0x000b0b +# ifdef WIN32 +# include <windows.h> +# else +# include <pthread.h> +# endif +#endif + +namespace Nan { + +#define NAN_INLINE inline // TODO(bnoordhuis) Remove in v3.0.0. + +#if defined(__GNUC__) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __attribute__((deprecated)) +#elif defined(_MSC_VER) && \ + !(defined(V8_DISABLE_DEPRECATIONS) && V8_DISABLE_DEPRECATIONS) +# define NAN_DEPRECATED __declspec(deprecated) +#else +# define NAN_DEPRECATED +#endif + +#if NAN_HAS_CPLUSPLUS_11 +# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&) = delete; +# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&) = delete; +# define NAN_DISALLOW_MOVE(CLASS) \ + CLASS(CLASS&&) = delete; /* NOLINT(build/c++11) */ \ + void operator=(CLASS&&) = delete; +#else +# define NAN_DISALLOW_ASSIGN(CLASS) void operator=(const CLASS&); +# define NAN_DISALLOW_COPY(CLASS) CLASS(const CLASS&); +# define NAN_DISALLOW_MOVE(CLASS) +#endif + +#define NAN_DISALLOW_ASSIGN_COPY(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_COPY(CLASS) + +#define NAN_DISALLOW_ASSIGN_MOVE(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define NAN_DISALLOW_COPY_MOVE(CLASS) \ + NAN_DISALLOW_COPY(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define NAN_DISALLOW_ASSIGN_COPY_MOVE(CLASS) \ + NAN_DISALLOW_ASSIGN(CLASS) \ + NAN_DISALLOW_COPY(CLASS) \ + NAN_DISALLOW_MOVE(CLASS) + +#define TYPE_CHECK(T, S) \ + while (false) { \ + *(static_cast<T *volatile *>(0)) = static_cast<S*>(0); \ + } + +//=== RegistrationFunction ===================================================== + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + typedef v8::Handle<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE; +#else + typedef v8::Local<v8::Object> ADDON_REGISTER_FUNCTION_ARGS_TYPE; +#endif + +#define NAN_MODULE_INIT(name) \ + void name(Nan::ADDON_REGISTER_FUNCTION_ARGS_TYPE target) + +//=== CallbackInfo ============================================================= + +#include "nan_callbacks.h" // NOLINT(build/include) + +//============================================================================== + +#if (NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION) +typedef v8::Script UnboundScript; +typedef v8::Script BoundScript; +#else +typedef v8::UnboundScript UnboundScript; +typedef v8::Script BoundScript; +#endif + +#if (NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION) +typedef v8::String::ExternalAsciiStringResource + ExternalOneByteStringResource; +#else +typedef v8::String::ExternalOneByteStringResource + ExternalOneByteStringResource; +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) +template<typename T> +class NonCopyablePersistentTraits : + public v8::NonCopyablePersistentTraits<T> {}; +template<typename T> +class CopyablePersistentTraits : + public v8::CopyablePersistentTraits<T> {}; + +template<typename T> +class PersistentBase : + public v8::PersistentBase<T> {}; + +template<typename T, typename M = v8::NonCopyablePersistentTraits<T> > +class Persistent; +#else +template<typename T> class NonCopyablePersistentTraits; +template<typename T> class PersistentBase; +template<typename T, typename P> class WeakCallbackData; +template<typename T, typename M = NonCopyablePersistentTraits<T> > +class Persistent; +#endif // NODE_MODULE_VERSION + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# include "nan_maybe_43_inl.h" // NOLINT(build/include) +#else +# include "nan_maybe_pre_43_inl.h" // NOLINT(build/include) +#endif + +#include "nan_converters.h" // NOLINT(build/include) +#include "nan_new.h" // NOLINT(build/include) + +#if NAUV_UVVERSION < 0x000b17 +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async, int) +#else +#define NAUV_WORK_CB(func) \ + void func(uv_async_t *async) +#endif + +#if NAUV_UVVERSION >= 0x000b0b + +typedef uv_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t *key) { + return uv_key_create(key); +} + +inline void nauv_key_delete(nauv_key_t *key) { + uv_key_delete(key); +} + +inline void* nauv_key_get(nauv_key_t *key) { + return uv_key_get(key); +} + +inline void nauv_key_set(nauv_key_t *key, void *value) { + uv_key_set(key, value); +} + +#else + +/* Implement thread local storage for older versions of libuv. + * This is essentially a backport of libuv commit 5d2434bf + * written by Ben Noordhuis, adjusted for names and inline. + */ + +#ifndef WIN32 + +typedef pthread_key_t nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + return -pthread_key_create(key, NULL); +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (pthread_key_delete(*key)) + abort(); +} + +inline void* nauv_key_get(nauv_key_t* key) { + return pthread_getspecific(*key); +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (pthread_setspecific(*key, value)) + abort(); +} + +#else + +typedef struct { + DWORD tls_index; +} nauv_key_t; + +inline int nauv_key_create(nauv_key_t* key) { + key->tls_index = TlsAlloc(); + if (key->tls_index == TLS_OUT_OF_INDEXES) + return UV_ENOMEM; + return 0; +} + +inline void nauv_key_delete(nauv_key_t* key) { + if (TlsFree(key->tls_index) == FALSE) + abort(); + key->tls_index = TLS_OUT_OF_INDEXES; +} + +inline void* nauv_key_get(nauv_key_t* key) { + void* value = TlsGetValue(key->tls_index); + if (value == NULL) + if (GetLastError() != ERROR_SUCCESS) + abort(); + return value; +} + +inline void nauv_key_set(nauv_key_t* key, void* value) { + if (TlsSetValue(key->tls_index, value) == FALSE) + abort(); +} + +#endif +#endif + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template<typename T> +v8::Local<T> New(v8::Handle<T>); +#endif + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + typedef v8::WeakCallbackType WeakCallbackType; +#else +struct WeakCallbackType { + enum E {kParameter, kInternalFields}; + E type; + WeakCallbackType(E other) : type(other) {} // NOLINT(runtime/explicit) + inline bool operator==(E other) { return other == this->type; } + inline bool operator!=(E other) { return !operator==(other); } +}; +#endif + +template<typename P> class WeakCallbackInfo; + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# include "nan_persistent_12_inl.h" // NOLINT(build/include) +#else +# include "nan_persistent_pre_12_inl.h" // NOLINT(build/include) +#endif + +namespace imp { + static const size_t kMaxLength = 0x3fffffff; + // v8::String::REPLACE_INVALID_UTF8 was introduced + // in node.js v0.10.29 and v0.8.27. +#if NODE_MAJOR_VERSION > 0 || \ + NODE_MINOR_VERSION > 10 || \ + NODE_MINOR_VERSION == 10 && NODE_PATCH_VERSION >= 29 || \ + NODE_MINOR_VERSION == 8 && NODE_PATCH_VERSION >= 27 + static const unsigned kReplaceInvalidUtf8 = v8::String::REPLACE_INVALID_UTF8; +#else + static const unsigned kReplaceInvalidUtf8 = 0; +#endif +} // end of namespace imp + +//=== HandleScope ============================================================== + +class HandleScope { + v8::HandleScope scope; + + public: +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + inline HandleScope() : scope(v8::Isolate::GetCurrent()) {} + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); + } +#else + inline HandleScope() : scope() {} + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(); + } +#endif + + private: + // Make it hard to create heap-allocated or illegal handle scopes by + // disallowing certain operations. + HandleScope(const HandleScope &); + void operator=(const HandleScope &); + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } +}; + +class EscapableHandleScope { + public: +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + inline EscapableHandleScope() : scope(v8::Isolate::GetCurrent()) {} + + inline static int NumberOfHandles() { + return v8::EscapableHandleScope::NumberOfHandles(v8::Isolate::GetCurrent()); + } + + template<typename T> + inline v8::Local<T> Escape(v8::Local<T> value) { + return scope.Escape(value); + } + + private: + v8::EscapableHandleScope scope; +#else + inline EscapableHandleScope() : scope() {} + + inline static int NumberOfHandles() { + return v8::HandleScope::NumberOfHandles(); + } + + template<typename T> + inline v8::Local<T> Escape(v8::Local<T> value) { + return scope.Close(value); + } + + private: + v8::HandleScope scope; +#endif + + private: + // Make it hard to create heap-allocated or illegal handle scopes by + // disallowing certain operations. + EscapableHandleScope(const EscapableHandleScope &); + void operator=(const EscapableHandleScope &); + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } +}; + +//=== TryCatch ================================================================= + +class TryCatch { + v8::TryCatch try_catch_; + friend void FatalException(const TryCatch&); + + public: +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + TryCatch() : try_catch_(v8::Isolate::GetCurrent()) {} +#endif + + inline bool HasCaught() const { return try_catch_.HasCaught(); } + + inline bool CanContinue() const { return try_catch_.CanContinue(); } + + inline v8::Local<v8::Value> ReThrow() { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + return New(try_catch_.ReThrow()); +#else + return try_catch_.ReThrow(); +#endif + } + + inline v8::Local<v8::Value> Exception() const { + return try_catch_.Exception(); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline v8::MaybeLocal<v8::Value> StackTrace() const { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(try_catch_.StackTrace(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } +#else + inline MaybeLocal<v8::Value> StackTrace() const { + return try_catch_.StackTrace(); + } +#endif + + inline v8::Local<v8::Message> Message() const { + return try_catch_.Message(); + } + + inline void Reset() { try_catch_.Reset(); } + + inline void SetVerbose(bool value) { try_catch_.SetVerbose(value); } + + inline void SetCaptureMessage(bool value) { + try_catch_.SetCaptureMessage(value); + } +}; + +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::Function> func, + int argc, + v8::Local<v8::Value>* argv); +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + v8::Local<v8::String> symbol, + int argc, + v8::Local<v8::Value>* argv); +v8::Local<v8::Value> MakeCallback(v8::Local<v8::Object> target, + const char* method, + int argc, + v8::Local<v8::Value>* argv); + +// === AsyncResource =========================================================== + +class AsyncResource { + public: + AsyncResource( + v8::Local<v8::String> name + , v8::Local<v8::Object> resource = New<v8::Object>()) { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + + if (resource.IsEmpty()) { + resource = New<v8::Object>(); + } + + context = node::EmitAsyncInit(isolate, resource, name); +#endif + } + + AsyncResource( + const char* name + , v8::Local<v8::Object> resource = New<v8::Object>()) { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + + if (resource.IsEmpty()) { + resource = New<v8::Object>(); + } + + v8::Local<v8::String> name_string = + New<v8::String>(name).ToLocalChecked(); + context = node::EmitAsyncInit(isolate, resource, name_string); +#endif + } + + ~AsyncResource() { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::EmitAsyncDestroy(isolate, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, func, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, symbol, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv, context); +#endif + } + + inline MaybeLocal<v8::Value> runInAsyncScope( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < NODE_9_0_MODULE_VERSION + return MakeCallback(target, method, argc, argv); +#else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv, context); +#endif + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncResource) +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + node::async_context context; +#endif +}; + +//============ ================================================================= + +/* node 0.12 */ +#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION + inline + void SetCounterFunction(v8::CounterLookupCallback cb) { + v8::Isolate::GetCurrent()->SetCounterFunction(cb); + } + + inline + void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::Isolate::GetCurrent()->SetCreateHistogramFunction(cb); + } + + inline + void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::Isolate::GetCurrent()->SetAddHistogramSampleFunction(cb); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline bool IdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotificationDeadline( + idle_time_in_ms * 0.001); + } +# else + inline bool IdleNotification(int idle_time_in_ms) { + return v8::Isolate::GetCurrent()->IdleNotification(idle_time_in_ms); + } +#endif + + inline void LowMemoryNotification() { + v8::Isolate::GetCurrent()->LowMemoryNotification(); + } + + inline void ContextDisposedNotification() { + v8::Isolate::GetCurrent()->ContextDisposedNotification(); + } +#else + inline + void SetCounterFunction(v8::CounterLookupCallback cb) { + v8::V8::SetCounterFunction(cb); + } + + inline + void SetCreateHistogramFunction(v8::CreateHistogramCallback cb) { + v8::V8::SetCreateHistogramFunction(cb); + } + + inline + void SetAddHistogramSampleFunction(v8::AddHistogramSampleCallback cb) { + v8::V8::SetAddHistogramSampleFunction(cb); + } + + inline bool IdleNotification(int idle_time_in_ms) { + return v8::V8::IdleNotification(idle_time_in_ms); + } + + inline void LowMemoryNotification() { + v8::V8::LowMemoryNotification(); + } + + inline void ContextDisposedNotification() { + v8::V8::ContextDisposedNotification(); + } +#endif + +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) // Node 0.12 + inline v8::Local<v8::Primitive> Undefined() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::Undefined(v8::Isolate::GetCurrent()))); +# else + return v8::Undefined(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Primitive> Null() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::Null(v8::Isolate::GetCurrent()))); +# else + return v8::Null(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Boolean> True() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::True(v8::Isolate::GetCurrent()))); +# else + return v8::True(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::Boolean> False() { +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(v8::False(v8::Isolate::GetCurrent()))); +# else + return v8::False(v8::Isolate::GetCurrent()); +# endif + } + + inline v8::Local<v8::String> EmptyString() { + return v8::String::Empty(v8::Isolate::GetCurrent()); + } + + inline int AdjustExternalMemory(int bc) { + return static_cast<int>( + v8::Isolate::GetCurrent()->AdjustAmountOfExternalAllocatedMemory(bc)); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , const char *name + , v8::Local<v8::Data> value) { + templ->Set(v8::Isolate::GetCurrent(), name, value); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + inline v8::Local<v8::Context> GetCurrentContext() { + return v8::Isolate::GetCurrent()->GetCurrentContext(); + } + + inline void* GetInternalFieldPointer( + v8::Local<v8::Object> object + , int index) { + return object->GetAlignedPointerFromInternalField(index); + } + + inline void SetInternalFieldPointer( + v8::Local<v8::Object> object + , int index + , void* value) { + object->SetAlignedPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::Isolate *isolate, v8::GCType type, v8::GCCallbackFlags flags) + +#if NODE_MODULE_VERSION <= NODE_4_0_MODULE_VERSION + typedef v8::Isolate::GCEpilogueCallback GCEpilogueCallback; + typedef v8::Isolate::GCPrologueCallback GCPrologueCallback; +#else + typedef v8::Isolate::GCCallback GCEpilogueCallback; + typedef v8::Isolate::GCCallback GCPrologueCallback; +#endif + + inline void AddGCEpilogueCallback( + GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCEpilogueCallback(callback, gc_type_filter); + } + + inline void RemoveGCEpilogueCallback( + GCEpilogueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCEpilogueCallback(callback); + } + + inline void AddGCPrologueCallback( + GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::Isolate::GetCurrent()->AddGCPrologueCallback(callback, gc_type_filter); + } + + inline void RemoveGCPrologueCallback( + GCPrologueCallback callback) { + v8::Isolate::GetCurrent()->RemoveGCPrologueCallback(callback); + } + + inline void GetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::Isolate::GetCurrent()->GetHeapStatistics(heap_statistics); + } + +# define X(NAME) \ + inline v8::Local<v8::Value> NAME(const char *msg) { \ + EscapableHandleScope scope; \ + return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \ + return v8::Exception::NAME(msg); \ + } \ + \ + inline void Throw ## NAME(const char *msg) { \ + HandleScope scope; \ + v8::Isolate::GetCurrent()->ThrowException( \ + v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline void Throw ## NAME(v8::Local<v8::String> msg) { \ + HandleScope scope; \ + v8::Isolate::GetCurrent()->ThrowException( \ + v8::Exception::NAME(msg)); \ + } + + X(Error) + X(RangeError) + X(ReferenceError) + X(SyntaxError) + X(TypeError) + +# undef X + + inline void ThrowError(v8::Local<v8::Value> error) { + v8::Isolate::GetCurrent()->ThrowException(error); + } + + inline MaybeLocal<v8::Object> NewBuffer( + char *data + , size_t length +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + , node::Buffer::FreeCallback callback +#else + , node::smalloc::FreeCallback callback +#endif + , void *hint + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(length <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New( + v8::Isolate::GetCurrent(), data, length, callback, hint); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), data, length, callback, + hint); +#endif + } + + inline MaybeLocal<v8::Object> CopyBuffer( + const char *data + , uint32_t size + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::Copy( + v8::Isolate::GetCurrent(), data, size); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New( + v8::Isolate::GetCurrent(), size); +#else + return node::Buffer::New(v8::Isolate::GetCurrent(), size); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer( + char* data + , uint32_t size + ) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION > IOJS_2_0_MODULE_VERSION + return node::Buffer::New(v8::Isolate::GetCurrent(), data, size); +#else + return node::Buffer::Use(v8::Isolate::GetCurrent(), data, size); +#endif + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::NewStringType::kNormal, length); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source source(s, origin); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) + .FromMaybe(v8::Local<BoundScript>())); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source source(s); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &source) + .FromMaybe(v8::Local<BoundScript>())); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<UnboundScript> script + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(script->BindToCurrentContext() + ->Run(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<BoundScript> script + ) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(script->Run(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Value>())); + } +#else + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + return v8::String::NewFromOneByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + v8::ScriptCompiler::Source source(s, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + v8::ScriptCompiler::Source source(s); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &source); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<UnboundScript> script + ) { + EscapableHandleScope scope; + return scope.Escape(script->BindToCurrentContext()->Run()); + } + + inline MaybeLocal<v8::Value> RunScript( + v8::Local<BoundScript> script + ) { + return script->Run(); + } +#endif + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, func, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, func, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, symbol, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, symbol, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + return scope.Escape(New(node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv))); +#else +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource res("nan:makeCallback"); + return res.runInAsyncScope(target, method, argc, argv) + .FromMaybe(v8::Local<v8::Value>()); +# else + return node::MakeCallback( + v8::Isolate::GetCurrent(), target, method, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#endif // NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + } + + inline void FatalException(const TryCatch& try_catch) { + node::FatalException(v8::Isolate::GetCurrent(), try_catch.try_catch_); + } + + inline v8::Local<v8::Value> ErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return node::ErrnoException(v8::Isolate::GetCurrent(), errorno, syscall, + message, path); + } + + NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return ErrnoException(errorno, syscall, message, path); + } + + template<typename T> + inline void SetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(0, data); + } + + template<typename T> + inline T *GetIsolateData( + v8::Isolate *isolate + ) { + return static_cast<T*>(isolate->GetData(0)); + } + +class Utf8String { + public: + inline explicit Utf8String(v8::Local<v8::Value> from) : + length_(0), str_(str_st_) { + HandleScope scope; + if (!from.IsEmpty()) { + v8::Local<v8::String> string = from->ToString(); + if (!string.IsEmpty()) { + size_t len = 3 * string->Length() + 1; + assert(len <= INT_MAX); + if (len > sizeof (str_st_)) { + str_ = static_cast<char*>(malloc(len)); + assert(str_ != 0); + } + const int flags = + v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; + length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags); + str_[length_] = '\0'; + } + } + } + + inline int length() const { + return length_; + } + + inline char* operator*() { return str_; } + inline const char* operator*() const { return str_; } + + inline ~Utf8String() { + if (str_ != str_st_) { + free(str_); + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) + + int length_; + char *str_; + char str_st_[1024]; +}; + +#else // Node 0.8 and 0.10 + inline v8::Local<v8::Primitive> Undefined() { + EscapableHandleScope scope; + return scope.Escape(New(v8::Undefined())); + } + + inline v8::Local<v8::Primitive> Null() { + EscapableHandleScope scope; + return scope.Escape(New(v8::Null())); + } + + inline v8::Local<v8::Boolean> True() { + EscapableHandleScope scope; + return scope.Escape(New(v8::True())); + } + + inline v8::Local<v8::Boolean> False() { + EscapableHandleScope scope; + return scope.Escape(New(v8::False())); + } + + inline v8::Local<v8::String> EmptyString() { + return v8::String::Empty(); + } + + inline int AdjustExternalMemory(int bc) { + return static_cast<int>(v8::V8::AdjustAmountOfExternalAllocatedMemory(bc)); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , const char *name + , v8::Local<v8::Data> value) { + templ->Set(name, value); + } + + inline void SetTemplate( + v8::Local<v8::Template> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes) { + templ->Set(name, value, attributes); + } + + inline v8::Local<v8::Context> GetCurrentContext() { + return v8::Context::GetCurrent(); + } + + inline void* GetInternalFieldPointer( + v8::Local<v8::Object> object + , int index) { + return object->GetPointerFromInternalField(index); + } + + inline void SetInternalFieldPointer( + v8::Local<v8::Object> object + , int index + , void* value) { + object->SetPointerInInternalField(index, value); + } + +# define NAN_GC_CALLBACK(name) \ + void name(v8::GCType type, v8::GCCallbackFlags flags) + + inline void AddGCEpilogueCallback( + v8::GCEpilogueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCEpilogueCallback(callback, gc_type_filter); + } + inline void RemoveGCEpilogueCallback( + v8::GCEpilogueCallback callback) { + v8::V8::RemoveGCEpilogueCallback(callback); + } + inline void AddGCPrologueCallback( + v8::GCPrologueCallback callback + , v8::GCType gc_type_filter = v8::kGCTypeAll) { + v8::V8::AddGCPrologueCallback(callback, gc_type_filter); + } + inline void RemoveGCPrologueCallback( + v8::GCPrologueCallback callback) { + v8::V8::RemoveGCPrologueCallback(callback); + } + inline void GetHeapStatistics( + v8::HeapStatistics *heap_statistics) { + v8::V8::GetHeapStatistics(heap_statistics); + } + +# define X(NAME) \ + inline v8::Local<v8::Value> NAME(const char *msg) { \ + EscapableHandleScope scope; \ + return scope.Escape(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + v8::Local<v8::Value> NAME(v8::Local<v8::String> msg) { \ + return v8::Exception::NAME(msg); \ + } \ + \ + inline void Throw ## NAME(const char *msg) { \ + HandleScope scope; \ + v8::ThrowException(v8::Exception::NAME(New(msg).ToLocalChecked())); \ + } \ + \ + inline \ + void Throw ## NAME(v8::Local<v8::String> errmsg) { \ + HandleScope scope; \ + v8::ThrowException(v8::Exception::NAME(errmsg)); \ + } + + X(Error) + X(RangeError) + X(ReferenceError) + X(SyntaxError) + X(TypeError) + +# undef X + + inline void ThrowError(v8::Local<v8::Value> error) { + v8::ThrowException(error); + } + + inline MaybeLocal<v8::Object> NewBuffer( + char *data + , size_t length + , node::Buffer::free_callback callback + , void *hint + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(length <= imp::kMaxLength && "too large buffer"); + return scope.Escape( + New(node::Buffer::New(data, length, callback, hint)->handle_)); + } + + inline MaybeLocal<v8::Object> CopyBuffer( + const char *data + , uint32_t size + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); +#if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return scope.Escape(New(node::Buffer::New(data, size)->handle_)); +#else + return scope.Escape( + New(node::Buffer::New(const_cast<char *>(data), size)->handle_)); +#endif + } + + inline MaybeLocal<v8::Object> NewBuffer(uint32_t size) { + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + EscapableHandleScope scope; + assert(size <= imp::kMaxLength && "too large buffer"); + return scope.Escape(New(node::Buffer::New(size)->handle_)); + } + + inline void FreeData(char *data, void *hint) { + (void) hint; // unused + delete[] data; + } + + inline MaybeLocal<v8::Object> NewBuffer( + char* data + , uint32_t size + ) { + EscapableHandleScope scope; + // arbitrary buffer lengths requires + // NODE_MODULE_VERSION >= IOJS_3_0_MODULE_VERSION + assert(size <= imp::kMaxLength && "too large buffer"); + return scope.Escape( + New(node::Buffer::New(data, size, FreeData, NULL)->handle_)); + } + +namespace imp { +inline void +widenString(std::vector<uint16_t> *ws, const uint8_t *s, int l) { + size_t len = static_cast<size_t>(l); + if (l < 0) { + len = strlen(reinterpret_cast<const char*>(s)); + } + assert(len <= INT_MAX && "string too long"); + ws->resize(len); + std::copy(s, s + len, ws->begin()); // NOLINT(build/include_what_you_use) +} +} // end of namespace imp + + inline MaybeLocal<v8::String> + NewOneByteString(const uint8_t * value, int length = -1) { + std::vector<uint16_t> wideString; // NOLINT(build/include_what_you_use) + imp::widenString(&wideString, value, length); + return v8::String::New(wideString.data(), + static_cast<int>(wideString.size())); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + , const v8::ScriptOrigin& origin + ) { + return v8::Script::Compile(s, const_cast<v8::ScriptOrigin *>(&origin)); + } + + inline MaybeLocal<BoundScript> CompileScript( + v8::Local<v8::String> s + ) { + return v8::Script::Compile(s); + } + + inline + MaybeLocal<v8::Value> RunScript(v8::Local<v8::Script> script) { + return script->Run(); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::Function> func + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, func, argc, argv))); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , v8::Local<v8::String> symbol + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, symbol, argc, argv))); + } + + inline v8::Local<v8::Value> MakeCallback( + v8::Local<v8::Object> target + , const char* method + , int argc + , v8::Local<v8::Value>* argv) { + v8::HandleScope scope; + return scope.Close(New(node::MakeCallback(target, method, argc, argv))); + } + + inline void FatalException(const TryCatch& try_catch) { + node::FatalException(const_cast<v8::TryCatch &>(try_catch.try_catch_)); + } + + inline v8::Local<v8::Value> ErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return node::ErrnoException(errorno, syscall, message, path); + } + + NAN_DEPRECATED inline v8::Local<v8::Value> NanErrnoException( + int errorno + , const char* syscall = NULL + , const char* message = NULL + , const char* path = NULL) { + return ErrnoException(errorno, syscall, message, path); + } + + + template<typename T> + inline void SetIsolateData( + v8::Isolate *isolate + , T *data + ) { + isolate->SetData(data); + } + + template<typename T> + inline T *GetIsolateData( + v8::Isolate *isolate + ) { + return static_cast<T*>(isolate->GetData()); + } + +class Utf8String { + public: + inline explicit Utf8String(v8::Local<v8::Value> from) : + length_(0), str_(str_st_) { + v8::HandleScope scope; + if (!from.IsEmpty()) { + v8::Local<v8::String> string = from->ToString(); + if (!string.IsEmpty()) { + size_t len = 3 * string->Length() + 1; + assert(len <= INT_MAX); + if (len > sizeof (str_st_)) { + str_ = static_cast<char*>(malloc(len)); + assert(str_ != 0); + } + const int flags = + v8::String::NO_NULL_TERMINATION | imp::kReplaceInvalidUtf8; + length_ = string->WriteUtf8(str_, static_cast<int>(len), 0, flags); + str_[length_] = '\0'; + } + } + } + + inline int length() const { + return length_; + } + + inline char* operator*() { return str_; } + inline const char* operator*() const { return str_; } + + inline ~Utf8String() { + if (str_ != str_st_) { + free(str_); + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Utf8String) + + int length_; + char *str_; + char str_st_[1024]; +}; + +#endif // NODE_MODULE_VERSION + +typedef void (*FreeCallback)(char *data, void *hint); + +typedef const FunctionCallbackInfo<v8::Value>& NAN_METHOD_ARGS_TYPE; +typedef void NAN_METHOD_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_GETTER_ARGS_TYPE; +typedef void NAN_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<void>& NAN_SETTER_ARGS_TYPE; +typedef void NAN_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& + NAN_PROPERTY_GETTER_ARGS_TYPE; +typedef void NAN_PROPERTY_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& + NAN_PROPERTY_SETTER_ARGS_TYPE; +typedef void NAN_PROPERTY_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Array>& + NAN_PROPERTY_ENUMERATOR_ARGS_TYPE; +typedef void NAN_PROPERTY_ENUMERATOR_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Boolean>& + NAN_PROPERTY_DELETER_ARGS_TYPE; +typedef void NAN_PROPERTY_DELETER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Integer>& + NAN_PROPERTY_QUERY_ARGS_TYPE; +typedef void NAN_PROPERTY_QUERY_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_GETTER_ARGS_TYPE; +typedef void NAN_INDEX_GETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Value>& NAN_INDEX_SETTER_ARGS_TYPE; +typedef void NAN_INDEX_SETTER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Array>& + NAN_INDEX_ENUMERATOR_ARGS_TYPE; +typedef void NAN_INDEX_ENUMERATOR_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Boolean>& + NAN_INDEX_DELETER_ARGS_TYPE; +typedef void NAN_INDEX_DELETER_RETURN_TYPE; + +typedef const PropertyCallbackInfo<v8::Integer>& + NAN_INDEX_QUERY_ARGS_TYPE; +typedef void NAN_INDEX_QUERY_RETURN_TYPE; + +#define NAN_METHOD(name) \ + Nan::NAN_METHOD_RETURN_TYPE name(Nan::NAN_METHOD_ARGS_TYPE info) +#define NAN_GETTER(name) \ + Nan::NAN_GETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_GETTER_ARGS_TYPE info) +#define NAN_SETTER(name) \ + Nan::NAN_SETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , v8::Local<v8::Value> value \ + , Nan::NAN_SETTER_ARGS_TYPE info) +#define NAN_PROPERTY_GETTER(name) \ + Nan::NAN_PROPERTY_GETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_GETTER_ARGS_TYPE info) +#define NAN_PROPERTY_SETTER(name) \ + Nan::NAN_PROPERTY_SETTER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , v8::Local<v8::Value> value \ + , Nan::NAN_PROPERTY_SETTER_ARGS_TYPE info) +#define NAN_PROPERTY_ENUMERATOR(name) \ + Nan::NAN_PROPERTY_ENUMERATOR_RETURN_TYPE name( \ + Nan::NAN_PROPERTY_ENUMERATOR_ARGS_TYPE info) +#define NAN_PROPERTY_DELETER(name) \ + Nan::NAN_PROPERTY_DELETER_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_DELETER_ARGS_TYPE info) +#define NAN_PROPERTY_QUERY(name) \ + Nan::NAN_PROPERTY_QUERY_RETURN_TYPE name( \ + v8::Local<v8::String> property \ + , Nan::NAN_PROPERTY_QUERY_ARGS_TYPE info) +# define NAN_INDEX_GETTER(name) \ + Nan::NAN_INDEX_GETTER_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_GETTER_ARGS_TYPE info) +#define NAN_INDEX_SETTER(name) \ + Nan::NAN_INDEX_SETTER_RETURN_TYPE name( \ + uint32_t index \ + , v8::Local<v8::Value> value \ + , Nan::NAN_INDEX_SETTER_ARGS_TYPE info) +#define NAN_INDEX_ENUMERATOR(name) \ + Nan::NAN_INDEX_ENUMERATOR_RETURN_TYPE \ + name(Nan::NAN_INDEX_ENUMERATOR_ARGS_TYPE info) +#define NAN_INDEX_DELETER(name) \ + Nan::NAN_INDEX_DELETER_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_DELETER_ARGS_TYPE info) +#define NAN_INDEX_QUERY(name) \ + Nan::NAN_INDEX_QUERY_RETURN_TYPE name( \ + uint32_t index \ + , Nan::NAN_INDEX_QUERY_ARGS_TYPE info) + +class Callback { + public: + Callback() {} + + explicit Callback(const v8::Local<v8::Function> &fn) : handle_(fn) {} + + ~Callback() { + handle_.Reset(); + } + + bool operator==(const Callback &other) const { + return handle_ == other.handle_; + } + + bool operator!=(const Callback &other) const { + return !operator==(other); + } + + inline + v8::Local<v8::Function> operator*() const { return GetFunction(); } + + NAN_DEPRECATED inline v8::Local<v8::Value> operator()( + v8::Local<v8::Object> target + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:operator()"); + return Call_(isolate, target, argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return Call_(isolate, target, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + return Call_(target, argc, argv); +#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + } + + NAN_DEPRECATED inline v8::Local<v8::Value> operator()( + int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:operator()"); + return scope.Escape(Call_(isolate, isolate->GetCurrentContext()->Global(), + argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>())); +# else + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif // NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + } + + inline MaybeLocal<v8::Value> operator()( + AsyncResource* resource + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { + return this->Call(argc, argv, resource); + } + + inline MaybeLocal<v8::Value> operator()( + AsyncResource* resource + , v8::Local<v8::Object> target + , int argc = 0 + , v8::Local<v8::Value> argv[] = 0) const { + return this->Call(target, argc, argv, resource); + } + + // TODO(kkoopa): remove + inline void SetFunction(const v8::Local<v8::Function> &fn) { + Reset(fn); + } + + inline void Reset(const v8::Local<v8::Function> &fn) { + handle_.Reset(fn); + } + + inline void Reset() { + handle_.Reset(); + } + + inline v8::Local<v8::Function> GetFunction() const { + return New(handle_); + } + + inline bool IsEmpty() const { + return handle_.IsEmpty(); + } + + // Deprecated: For async callbacks Use the versions that accept an + // AsyncResource. If this callback does not correspond to an async resource, + // that is, it is a synchronous function call on a non-empty JS stack, you + // should Nan::Call instead. + NAN_DEPRECATED inline v8::Local<v8::Value> + Call(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:Call"); + return Call_(isolate, target, argc, argv, &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return Call_(isolate, target, argc, argv); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + return Call_(target, argc, argv); +#endif + } + + // Deprecated: For async callbacks Use the versions that accept an + // AsyncResource. If this callback does not correspond to an async resource, + // that is, it is a synchronous function call on a non-empty JS stack, you + // should Nan::Call instead. + NAN_DEPRECATED inline v8::Local<v8::Value> + Call(int argc, v8::Local<v8::Value> argv[]) const { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); +# if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + AsyncResource async("nan:Callback:Call"); + return Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv, + &async) + .FromMaybe(v8::Local<v8::Value>()); +# else + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +# endif // NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif + } + + inline MaybeLocal<v8::Value> + Call(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[] + , AsyncResource* resource) const { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv, resource); +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + return Call_(isolate, target, argc, argv); +#else + return Call_(target, argc, argv); +#endif + } + + inline MaybeLocal<v8::Value> + Call(int argc, v8::Local<v8::Value> argv[], AsyncResource* resource) const { +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + return Call(isolate->GetCurrentContext()->Global(), argc, argv, resource); +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + Call_(isolate, isolate->GetCurrentContext()->Global(), argc, argv)); +#else + v8::HandleScope scope; + return scope.Close(Call_(v8::Context::GetCurrent()->Global(), argc, argv)); +#endif + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(Callback) + Persistent<v8::Function> handle_; + +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + MaybeLocal<v8::Value> Call_(v8::Isolate *isolate + , v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[] + , AsyncResource* resource) const { + EscapableHandleScope scope; + v8::Local<v8::Function> func = New(handle_); + auto maybe = resource->runInAsyncScope(target, func, argc, argv); + v8::Local<v8::Value> local; + if (!maybe.ToLocal(&local)) return MaybeLocal<v8::Value>(); + return scope.Escape(local); + } +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Local<v8::Value> Call_(v8::Isolate *isolate + , v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { + EscapableHandleScope scope; + + v8::Local<v8::Function> callback = New(handle_); +# if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION + return scope.Escape(New(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + ))); +# else + return scope.Escape(node::MakeCallback( + isolate + , target + , callback + , argc + , argv + )); +# endif + } +#else + v8::Local<v8::Value> Call_(v8::Local<v8::Object> target + , int argc + , v8::Local<v8::Value> argv[]) const { + EscapableHandleScope scope; + + v8::Local<v8::Function> callback = New(handle_); + return scope.Escape(New(node::MakeCallback( + target + , callback + , argc + , argv + ))); + } +#endif +}; + +inline MaybeLocal<v8::Value> Call( + const Nan::Callback& callback + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + return Call(*callback, recv, argc, argv); +} + +inline MaybeLocal<v8::Value> Call( + const Nan::Callback& callback + , int argc + , v8::Local<v8::Value> argv[]) { +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + Call(*callback, isolate->GetCurrentContext()->Global(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +#else + EscapableHandleScope scope; + return scope.Escape( + Call(*callback, v8::Context::GetCurrent()->Global(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +#endif +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::String> symbol + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + EscapableHandleScope scope; + v8::Local<v8::Value> fn_v = + Get(recv, symbol).FromMaybe(v8::Local<v8::Value>()); + if (fn_v.IsEmpty() || !fn_v->IsFunction()) return v8::Local<v8::Value>(); + v8::Local<v8::Function> fn = fn_v.As<v8::Function>(); + return scope.Escape( + Call(fn, recv, argc, argv).FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> Call( + const char* method + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + EscapableHandleScope scope; + v8::Local<v8::String> method_string = + New<v8::String>(method).ToLocalChecked(); + return scope.Escape( + Call(method_string, recv, argc, argv).FromMaybe(v8::Local<v8::Value>())); +} + +/* abstract */ class AsyncWorker { + public: + explicit AsyncWorker(Callback *callback_, + const char* resource_name = "nan:AsyncWorker") + : callback(callback_), errmsg_(NULL) { + request.data = this; + + HandleScope scope; + v8::Local<v8::Object> obj = New<v8::Object>(); + persistentHandle.Reset(obj); + async_resource = new AsyncResource(resource_name, obj); + } + + virtual ~AsyncWorker() { + HandleScope scope; + + if (!persistentHandle.IsEmpty()) + persistentHandle.Reset(); + delete callback; + delete[] errmsg_; + delete async_resource; + } + + virtual void WorkComplete() { + HandleScope scope; + + if (errmsg_ == NULL) + HandleOKCallback(); + else + HandleErrorCallback(); + delete callback; + callback = NULL; + } + + inline void SaveToPersistent( + const char *key, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(New(key).ToLocalChecked(), value); + } + + inline void SaveToPersistent( + const v8::Local<v8::String> &key, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(key, value); + } + + inline void SaveToPersistent( + uint32_t index, const v8::Local<v8::Value> &value) { + HandleScope scope; + New(persistentHandle)->Set(index, value); + } + + inline v8::Local<v8::Value> GetFromPersistent(const char *key) const { + EscapableHandleScope scope; + return scope.Escape( + New(persistentHandle)->Get(New(key).ToLocalChecked())); + } + + inline v8::Local<v8::Value> + GetFromPersistent(const v8::Local<v8::String> &key) const { + EscapableHandleScope scope; + return scope.Escape(New(persistentHandle)->Get(key)); + } + + inline v8::Local<v8::Value> GetFromPersistent(uint32_t index) const { + EscapableHandleScope scope; + return scope.Escape(New(persistentHandle)->Get(index)); + } + + virtual void Execute() = 0; + + uv_work_t request; + + virtual void Destroy() { + delete this; + } + + protected: + Persistent<v8::Object> persistentHandle; + Callback *callback; + AsyncResource *async_resource; + + virtual void HandleOKCallback() { + HandleScope scope; + + callback->Call(0, NULL, async_resource); + } + + virtual void HandleErrorCallback() { + HandleScope scope; + + v8::Local<v8::Value> argv[] = { + v8::Exception::Error(New<v8::String>(ErrorMessage()).ToLocalChecked()) + }; + callback->Call(1, argv, async_resource); + } + + void SetErrorMessage(const char *msg) { + delete[] errmsg_; + + size_t size = strlen(msg) + 1; + errmsg_ = new char[size]; + memcpy(errmsg_, msg, size); + } + + const char* ErrorMessage() const { + return errmsg_; + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(AsyncWorker) + char *errmsg_; +}; + +/* abstract */ class AsyncBareProgressWorkerBase : public AsyncWorker { + public: + explicit AsyncBareProgressWorkerBase( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressWorkerBase") + : AsyncWorker(callback_, resource_name) { + uv_async_init( + uv_default_loop() + , &async + , AsyncProgress_ + ); + async.data = this; + } + + virtual ~AsyncBareProgressWorkerBase() { + } + + virtual void WorkProgress() = 0; + + virtual void Destroy() { + uv_close(reinterpret_cast<uv_handle_t*>(&async), AsyncClose_); + } + + private: + inline static NAUV_WORK_CB(AsyncProgress_) { + AsyncBareProgressWorkerBase *worker = + static_cast<AsyncBareProgressWorkerBase*>(async->data); + worker->WorkProgress(); + } + + inline static void AsyncClose_(uv_handle_t* handle) { + AsyncBareProgressWorkerBase *worker = + static_cast<AsyncBareProgressWorkerBase*>(handle->data); + delete worker; + } + + protected: + uv_async_t async; +}; + +template<class T> +/* abstract */ +class AsyncBareProgressWorker : public AsyncBareProgressWorkerBase { + public: + explicit AsyncBareProgressWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressWorker") + : AsyncBareProgressWorkerBase(callback_, resource_name) { + } + + virtual ~AsyncBareProgressWorker() { + } + + class ExecutionProgress { + friend class AsyncBareProgressWorker; + public: + void Signal() const { + uv_async_send(&that_->async); + } + + void Send(const T* data, size_t count) const { + that_->SendProgress_(data, count); + } + + private: + explicit ExecutionProgress(AsyncBareProgressWorker *that) : that_(that) {} + NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) + AsyncBareProgressWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const T *data, size_t size) = 0; + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + virtual void SendProgress_(const T *data, size_t count) = 0; +}; + +template<class T> +/* abstract */ +class AsyncProgressWorkerBase : public AsyncBareProgressWorker<T> { + public: + explicit AsyncProgressWorkerBase( + Callback *callback_, + const char* resource_name = "nan:AsyncProgressWorkerBase") + : AsyncBareProgressWorker<T>(callback_, resource_name), asyncdata_(NULL), + asyncsize_(0) { + uv_mutex_init(&async_lock); + } + + virtual ~AsyncProgressWorkerBase() { + uv_mutex_destroy(&async_lock); + + delete[] asyncdata_; + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + T *data = asyncdata_; + size_t size = asyncsize_; + asyncdata_ = NULL; + uv_mutex_unlock(&async_lock); + + // Don't send progress events after we've already completed. + if (this->callback) { + this->HandleProgressCallback(data, size); + } + delete[] data; + } + + private: + void SendProgress_(const T *data, size_t count) { + T *new_data = new T[count]; + { + T *it = new_data; + std::copy(data, data + count, it); + } + + uv_mutex_lock(&async_lock); + T *old_data = asyncdata_; + asyncdata_ = new_data; + asyncsize_ = count; + uv_mutex_unlock(&async_lock); + + delete[] old_data; + uv_async_send(&this->async); + } + + uv_mutex_t async_lock; + T *asyncdata_; + size_t asyncsize_; +}; + +// This ensures compatibility to the previous un-templated AsyncProgressWorker +// class definition. +typedef AsyncProgressWorkerBase<char> AsyncProgressWorker; + +template<class T> +/* abstract */ +class AsyncBareProgressQueueWorker : public AsyncBareProgressWorkerBase { + public: + explicit AsyncBareProgressQueueWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncBareProgressQueueWorker") + : AsyncBareProgressWorkerBase(callback_, resource_name) { + } + + virtual ~AsyncBareProgressQueueWorker() { + } + + class ExecutionProgress { + friend class AsyncBareProgressQueueWorker; + public: + void Send(const T* data, size_t count) const { + that_->SendProgress_(data, count); + } + + private: + explicit ExecutionProgress(AsyncBareProgressQueueWorker *that) + : that_(that) {} + NAN_DISALLOW_ASSIGN_COPY_MOVE(ExecutionProgress) + AsyncBareProgressQueueWorker* const that_; + }; + + virtual void Execute(const ExecutionProgress& progress) = 0; + virtual void HandleProgressCallback(const T *data, size_t size) = 0; + + private: + void Execute() /*final override*/ { + ExecutionProgress progress(this); + Execute(progress); + } + + virtual void SendProgress_(const T *data, size_t count) = 0; +}; + +template<class T> +/* abstract */ +class AsyncProgressQueueWorker : public AsyncBareProgressQueueWorker<T> { + public: + explicit AsyncProgressQueueWorker( + Callback *callback_, + const char* resource_name = "nan:AsyncProgressQueueWorker") + : AsyncBareProgressQueueWorker<T>(callback_) { + uv_mutex_init(&async_lock); + } + + virtual ~AsyncProgressQueueWorker() { + uv_mutex_lock(&async_lock); + + while (!asyncdata_.empty()) { + std::pair<T*, size_t> &datapair = asyncdata_.front(); + T *data = datapair.first; + + asyncdata_.pop(); + + delete[] data; + } + + uv_mutex_unlock(&async_lock); + uv_mutex_destroy(&async_lock); + } + + void WorkComplete() { + WorkProgress(); + AsyncWorker::WorkComplete(); + } + + void WorkProgress() { + uv_mutex_lock(&async_lock); + + while (!asyncdata_.empty()) { + std::pair<T*, size_t> &datapair = asyncdata_.front(); + + T *data = datapair.first; + size_t size = datapair.second; + + asyncdata_.pop(); + uv_mutex_unlock(&async_lock); + + // Don't send progress events after we've already completed. + if (this->callback) { + this->HandleProgressCallback(data, size); + } + + delete[] data; + + uv_mutex_lock(&async_lock); + } + + uv_mutex_unlock(&async_lock); + } + + private: + void SendProgress_(const T *data, size_t count) { + T *new_data = new T[count]; + { + T *it = new_data; + std::copy(data, data + count, it); + } + + uv_mutex_lock(&async_lock); + asyncdata_.push(std::pair<T*, size_t>(new_data, count)); + uv_mutex_unlock(&async_lock); + + uv_async_send(&this->async); + } + + uv_mutex_t async_lock; + std::queue<std::pair<T*, size_t> > asyncdata_; +}; + +inline void AsyncExecute (uv_work_t* req) { + AsyncWorker *worker = static_cast<AsyncWorker*>(req->data); + worker->Execute(); +} + +inline void AsyncExecuteComplete (uv_work_t* req) { + AsyncWorker* worker = static_cast<AsyncWorker*>(req->data); + worker->WorkComplete(); + worker->Destroy(); +} + +inline void AsyncQueueWorker (AsyncWorker* worker) { + uv_queue_work( + uv_default_loop() + , &worker->request + , AsyncExecute + , reinterpret_cast<uv_after_work_cb>(AsyncExecuteComplete) + ); +} + +namespace imp { + +inline +ExternalOneByteStringResource const* +GetExternalResource(v8::Local<v8::String> str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->GetExternalAsciiStringResource(); +#else + return str->GetExternalOneByteStringResource(); +#endif +} + +inline +bool +IsExternal(v8::Local<v8::String> str) { +#if NODE_MODULE_VERSION < ATOM_0_21_MODULE_VERSION + return str->IsExternalAscii(); +#else + return str->IsExternalOneByte(); +#endif +} + +} // end of namespace imp + +enum Encoding {ASCII, UTF8, BASE64, UCS2, BINARY, HEX, BUFFER}; + +#if NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION +# include "nan_string_bytes.h" // NOLINT(build/include) +#endif + +inline v8::Local<v8::Value> Encode( + const void *buf, size_t len, enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION >= ATOM_0_21_MODULE_VERSION) + v8::Isolate* isolate = v8::Isolate::GetCurrent(); + node::encoding node_enc = static_cast<node::encoding>(encoding); + + if (encoding == UCS2) { + return node::Encode( + isolate + , reinterpret_cast<const uint16_t *>(buf) + , len / 2); + } else { + return node::Encode( + isolate + , reinterpret_cast<const char *>(buf) + , len + , node_enc); + } +#elif (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::Encode( + v8::Isolate::GetCurrent() + , buf, len + , static_cast<node::encoding>(encoding)); +#else +# if NODE_MODULE_VERSION >= NODE_0_10_MODULE_VERSION + return node::Encode(buf, len, static_cast<node::encoding>(encoding)); +# else + return imp::Encode(reinterpret_cast<const char*>(buf), len, encoding); +# endif +#endif +} + +inline ssize_t DecodeBytes( + v8::Local<v8::Value> val, enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeBytes( + v8::Isolate::GetCurrent() + , val + , static_cast<node::encoding>(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == BUFFER) { + return node::DecodeBytes(val, node::BINARY); + } +# endif + return node::DecodeBytes(val, static_cast<node::encoding>(encoding)); +#endif +} + +inline ssize_t DecodeWrite( + char *buf + , size_t len + , v8::Local<v8::Value> val + , enum Encoding encoding = BINARY) { +#if (NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION) + return node::DecodeWrite( + v8::Isolate::GetCurrent() + , buf + , len + , val + , static_cast<node::encoding>(encoding)); +#else +# if (NODE_MODULE_VERSION < NODE_0_10_MODULE_VERSION) + if (encoding == BUFFER) { + return node::DecodeWrite(buf, len, val, node::BINARY); + } +# endif + return node::DecodeWrite( + buf + , len + , val + , static_cast<node::encoding>(encoding)); +#endif +} + +inline void SetPrototypeTemplate( + v8::Local<v8::FunctionTemplate> templ + , const char *name + , v8::Local<v8::Data> value +) { + HandleScope scope; + SetTemplate(templ->PrototypeTemplate(), name, value); +} + +inline void SetPrototypeTemplate( + v8::Local<v8::FunctionTemplate> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes +) { + HandleScope scope; + SetTemplate(templ->PrototypeTemplate(), name, value, attributes); +} + +inline void SetInstanceTemplate( + v8::Local<v8::FunctionTemplate> templ + , const char *name + , v8::Local<v8::Data> value +) { + HandleScope scope; + SetTemplate(templ->InstanceTemplate(), name, value); +} + +inline void SetInstanceTemplate( + v8::Local<v8::FunctionTemplate> templ + , v8::Local<v8::String> name + , v8::Local<v8::Data> value + , v8::PropertyAttribute attributes +) { + HandleScope scope; + SetTemplate(templ->InstanceTemplate(), name, value, attributes); +} + +namespace imp { + +// Note(@agnat): Helper to distinguish different receiver types. The first +// version deals with receivers derived from v8::Template. The second version +// handles everything else. The final argument only serves as discriminator and +// is unused. +template <typename T> +inline +void +SetMethodAux(T recv, + v8::Local<v8::String> name, + v8::Local<v8::FunctionTemplate> tpl, + v8::Template *) { + recv->Set(name, tpl); +} + +template <typename T> +inline +void +SetMethodAux(T recv, + v8::Local<v8::String> name, + v8::Local<v8::FunctionTemplate> tpl, + ...) { + recv->Set(name, GetFunction(tpl).ToLocalChecked()); +} + +} // end of namespace imp + +template <typename T, template <typename> class HandleType> +inline void SetMethod( + HandleType<T> recv + , const char *name + , FunctionCallback callback) { + HandleScope scope; + v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>(callback); + v8::Local<v8::String> fn_name = New(name).ToLocalChecked(); + t->SetClassName(fn_name); + // Note(@agnat): Pass an empty T* as discriminator. See note on + // SetMethodAux(...) above + imp::SetMethodAux(recv, fn_name, t, static_cast<T*>(0)); +} + +inline void SetPrototypeMethod( + v8::Local<v8::FunctionTemplate> recv + , const char* name, FunctionCallback callback) { + HandleScope scope; + v8::Local<v8::FunctionTemplate> t = New<v8::FunctionTemplate>( + callback + , v8::Local<v8::Value>() + , New<v8::Signature>(recv)); + v8::Local<v8::String> fn_name = New(name).ToLocalChecked(); + recv->PrototypeTemplate()->Set(fn_name, t); + t->SetClassName(fn_name); +} + +//=== Accessors and Such ======================================================= + +inline void SetAccessor( + v8::Local<v8::ObjectTemplate> tpl + , v8::Local<v8::String> name + , GetterCallback getter + , SetterCallback setter = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::AccessControl settings = v8::DEFAULT + , v8::PropertyAttribute attribute = v8::None + , imp::Sig signature = imp::Sig()) { + HandleScope scope; + + imp::NativeGetter getter_ = + imp::GetterCallbackWrapper; + imp::NativeSetter setter_ = + setter ? imp::SetterCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kAccessorFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter != 0) { + obj->SetInternalField( + imp::kSetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetAccessor( + name + , getter_ + , setter_ + , obj + , settings + , attribute + , signature); +} + +inline bool SetAccessor( + v8::Local<v8::Object> obj + , v8::Local<v8::String> name + , GetterCallback getter + , SetterCallback setter = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::AccessControl settings = v8::DEFAULT + , v8::PropertyAttribute attribute = v8::None) { + HandleScope scope; + + imp::NativeGetter getter_ = + imp::GetterCallbackWrapper; + imp::NativeSetter setter_ = + setter ? imp::SetterCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kAccessorFieldCount); + v8::Local<v8::Object> dataobj = NewInstance(otpl).ToLocalChecked(); + + dataobj->SetInternalField( + imp::kGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (!data.IsEmpty()) { + dataobj->SetInternalField(imp::kDataIndex, data); + } + + if (setter) { + dataobj->SetInternalField( + imp::kSetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + return obj->SetAccessor( + GetCurrentContext() + , name + , getter_ + , setter_ + , dataobj + , settings + , attribute).FromMaybe(false); +#else + return obj->SetAccessor( + name + , getter_ + , setter_ + , dataobj + , settings + , attribute); +#endif +} + +inline void SetNamedPropertyHandler( + v8::Local<v8::ObjectTemplate> tpl + , PropertyGetterCallback getter + , PropertySetterCallback setter = 0 + , PropertyQueryCallback query = 0 + , PropertyDeleterCallback deleter = 0 + , PropertyEnumeratorCallback enumerator = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + imp::NativePropertyGetter getter_ = + imp::PropertyGetterCallbackWrapper; + imp::NativePropertySetter setter_ = + setter ? imp::PropertySetterCallbackWrapper : 0; + imp::NativePropertyQuery query_ = + query ? imp::PropertyQueryCallbackWrapper : 0; + imp::NativePropertyDeleter *deleter_ = + deleter ? imp::PropertyDeleterCallbackWrapper : 0; + imp::NativePropertyEnumerator enumerator_ = + enumerator ? imp::PropertyEnumeratorCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kPropertyFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + obj->SetInternalField( + imp::kPropertyGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter) { + obj->SetInternalField( + imp::kPropertySetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (query) { + obj->SetInternalField( + imp::kPropertyQueryIndex + , New<v8::External>(reinterpret_cast<void *>(query))); + } + + if (deleter) { + obj->SetInternalField( + imp::kPropertyDeleterIndex + , New<v8::External>(reinterpret_cast<void *>(deleter))); + } + + if (enumerator) { + obj->SetInternalField( + imp::kPropertyEnumeratorIndex + , New<v8::External>(reinterpret_cast<void *>(enumerator))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + tpl->SetHandler(v8::NamedPropertyHandlerConfiguration( + getter_, setter_, query_, deleter_, enumerator_, obj)); +#else + tpl->SetNamedPropertyHandler( + getter_ + , setter_ + , query_ + , deleter_ + , enumerator_ + , obj); +#endif +} + +inline void SetIndexedPropertyHandler( + v8::Local<v8::ObjectTemplate> tpl + , IndexGetterCallback getter + , IndexSetterCallback setter = 0 + , IndexQueryCallback query = 0 + , IndexDeleterCallback deleter = 0 + , IndexEnumeratorCallback enumerator = 0 + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + imp::NativeIndexGetter getter_ = + imp::IndexGetterCallbackWrapper; + imp::NativeIndexSetter setter_ = + setter ? imp::IndexSetterCallbackWrapper : 0; + imp::NativeIndexQuery query_ = + query ? imp::IndexQueryCallbackWrapper : 0; + imp::NativeIndexDeleter deleter_ = + deleter ? imp::IndexDeleterCallbackWrapper : 0; + imp::NativeIndexEnumerator enumerator_ = + enumerator ? imp::IndexEnumeratorCallbackWrapper : 0; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kIndexPropertyFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + obj->SetInternalField( + imp::kIndexPropertyGetterIndex + , New<v8::External>(reinterpret_cast<void *>(getter))); + + if (setter) { + obj->SetInternalField( + imp::kIndexPropertySetterIndex + , New<v8::External>(reinterpret_cast<void *>(setter))); + } + + if (query) { + obj->SetInternalField( + imp::kIndexPropertyQueryIndex + , New<v8::External>(reinterpret_cast<void *>(query))); + } + + if (deleter) { + obj->SetInternalField( + imp::kIndexPropertyDeleterIndex + , New<v8::External>(reinterpret_cast<void *>(deleter))); + } + + if (enumerator) { + obj->SetInternalField( + imp::kIndexPropertyEnumeratorIndex + , New<v8::External>(reinterpret_cast<void *>(enumerator))); + } + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + tpl->SetHandler(v8::IndexedPropertyHandlerConfiguration( + getter_, setter_, query_, deleter_, enumerator_, obj)); +#else + tpl->SetIndexedPropertyHandler( + getter_ + , setter_ + , query_ + , deleter_ + , enumerator_ + , obj); +#endif +} + +inline void SetCallHandler( + v8::Local<v8::FunctionTemplate> tpl + , FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , New<v8::External>(reinterpret_cast<void *>(callback))); + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetCallHandler(imp::FunctionCallbackWrapper, obj); +} + + +inline void SetCallAsFunctionHandler( + v8::Local<v8::ObjectTemplate> tpl, + FunctionCallback callback, + v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + HandleScope scope; + + v8::Local<v8::ObjectTemplate> otpl = New<v8::ObjectTemplate>(); + otpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(otpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , New<v8::External>(reinterpret_cast<void *>(callback))); + + if (!data.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, data); + } + + tpl->SetCallAsFunctionHandler(imp::FunctionCallbackWrapper, obj); +} + +//=== Weak Persistent Handling ================================================= + +#include "nan_weak.h" // NOLINT(build/include) + +//=== ObjectWrap =============================================================== + +#include "nan_object_wrap.h" // NOLINT(build/include) + +//=== HiddenValue/Private ====================================================== + +#include "nan_private.h" // NOLINT(build/include) + +//=== Export ================================================================== + +inline +void +Export(ADDON_REGISTER_FUNCTION_ARGS_TYPE target, const char *name, + FunctionCallback f) { + HandleScope scope; + + Set(target, New<v8::String>(name).ToLocalChecked(), + GetFunction(New<v8::FunctionTemplate>(f)).ToLocalChecked()); +} + +//=== Tap Reverse Binding ===================================================== + +struct Tap { + explicit Tap(v8::Local<v8::Value> t) : t_() { + HandleScope scope; + + t_.Reset(To<v8::Object>(t).ToLocalChecked()); + } + + ~Tap() { t_.Reset(); } // not sure if neccessary + + inline void plan(int i) { + HandleScope scope; + v8::Local<v8::Value> arg = New(i); + Call("plan", New(t_), 1, &arg); + } + + inline void ok(bool isOk, const char *msg = NULL) { + HandleScope scope; + v8::Local<v8::Value> args[2]; + args[0] = New(isOk); + if (msg) args[1] = New(msg).ToLocalChecked(); + Call("ok", New(t_), msg ? 2 : 1, args); + } + + inline void pass(const char * msg = NULL) { + HandleScope scope; + v8::Local<v8::Value> hmsg; + if (msg) hmsg = New(msg).ToLocalChecked(); + Call("pass", New(t_), msg ? 1 : 0, &hmsg); + } + + inline void end() { + HandleScope scope; + Call("end", New(t_), 0, NULL); + } + + private: + Persistent<v8::Object> t_; +}; + +#define NAN_STRINGIZE2(x) #x +#define NAN_STRINGIZE(x) NAN_STRINGIZE2(x) +#define NAN_TEST_EXPRESSION(expression) \ + ( expression ), __FILE__ ":" NAN_STRINGIZE(__LINE__) ": " #expression + +#define NAN_EXPORT(target, function) Export(target, #function, function) + +#undef TYPE_CHECK + +//=== Generic Maybefication =================================================== + +namespace imp { + +template <typename T> struct Maybefier; + +template <typename T> struct Maybefier<v8::Local<T> > { + inline static MaybeLocal<T> convert(v8::Local<T> v) { + return v; + } +}; + +template <typename T> struct Maybefier<MaybeLocal<T> > { + inline static MaybeLocal<T> convert(MaybeLocal<T> v) { + return v; + } +}; + +} // end of namespace imp + +template <typename T, template <typename> class MaybeMaybe> +inline MaybeLocal<T> +MakeMaybe(MaybeMaybe<T> v) { + return imp::Maybefier<MaybeMaybe<T> >::convert(v); +} + +//=== TypedArrayContents ======================================================= + +#include "nan_typedarray_contents.h" // NOLINT(build/include) + +//=== JSON ===================================================================== + +#include "nan_json.h" // NOLINT(build/include) + +} // end of namespace Nan + +#endif // NAN_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks.h new file mode 100644 index 0000000000000000000000000000000000000000..53ede846ac9a865a737218dabbbd48305d3d6b63 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks.h @@ -0,0 +1,88 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_H_ +#define NAN_CALLBACKS_H_ + +template<typename T> class FunctionCallbackInfo; +template<typename T> class PropertyCallbackInfo; +template<typename T> class Global; + +typedef void(*FunctionCallback)(const FunctionCallbackInfo<v8::Value>&); +typedef void(*GetterCallback) + (v8::Local<v8::String>, const PropertyCallbackInfo<v8::Value>&); +typedef void(*SetterCallback)( + v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<void>&); +typedef void(*PropertyGetterCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*PropertySetterCallback)( + v8::Local<v8::String>, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*PropertyEnumeratorCallback) + (const PropertyCallbackInfo<v8::Array>&); +typedef void(*PropertyDeleterCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Boolean>&); +typedef void(*PropertyQueryCallback)( + v8::Local<v8::String>, + const PropertyCallbackInfo<v8::Integer>&); +typedef void(*IndexGetterCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*IndexSetterCallback)( + uint32_t, + v8::Local<v8::Value>, + const PropertyCallbackInfo<v8::Value>&); +typedef void(*IndexEnumeratorCallback) + (const PropertyCallbackInfo<v8::Array>&); +typedef void(*IndexDeleterCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Boolean>&); +typedef void(*IndexQueryCallback)( + uint32_t, + const PropertyCallbackInfo<v8::Integer>&); + +namespace imp { +typedef v8::Local<v8::AccessorSignature> Sig; + +static const int kDataIndex = 0; + +static const int kFunctionIndex = 1; +static const int kFunctionFieldCount = 2; + +static const int kGetterIndex = 1; +static const int kSetterIndex = 2; +static const int kAccessorFieldCount = 3; + +static const int kPropertyGetterIndex = 1; +static const int kPropertySetterIndex = 2; +static const int kPropertyEnumeratorIndex = 3; +static const int kPropertyDeleterIndex = 4; +static const int kPropertyQueryIndex = 5; +static const int kPropertyFieldCount = 6; + +static const int kIndexPropertyGetterIndex = 1; +static const int kIndexPropertySetterIndex = 2; +static const int kIndexPropertyEnumeratorIndex = 3; +static const int kIndexPropertyDeleterIndex = 4; +static const int kIndexPropertyQueryIndex = 5; +static const int kIndexPropertyFieldCount = 6; + +} // end of namespace imp + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# include "nan_callbacks_12_inl.h" // NOLINT(build/include) +#else +# include "nan_callbacks_pre_12_inl.h" // NOLINT(build/include) +#endif + +#endif // NAN_CALLBACKS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..d3df79aaf0e21a6f175966e55b523823b704ba29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_12_inl.h @@ -0,0 +1,512 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_12_INL_H_ +#define NAN_CALLBACKS_12_INL_H_ + +template<typename T> +class ReturnValue { + v8::ReturnValue<T> value_; + + public: + template <class S> + explicit inline ReturnValue(const v8::ReturnValue<S> &value) : + value_(value) {} + template <class S> + explicit inline ReturnValue(const ReturnValue<S>& that) + : value_(that.value_) { + TYPE_CHECK(T, S); + } + + // Handle setters + template <typename S> inline void Set(const v8::Local<S> &handle) { + TYPE_CHECK(T, S); + value_.Set(handle); + } + + template <typename S> inline void Set(const Global<S> &handle) { + TYPE_CHECK(T, S); +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && \ + (V8_MINOR_VERSION > 5 || (V8_MINOR_VERSION == 5 && \ + defined(V8_BUILD_NUMBER) && V8_BUILD_NUMBER >= 8)))) + value_.Set(handle); +#else + value_.Set(*reinterpret_cast<const v8::Persistent<S>*>(&handle)); + const_cast<Global<S> &>(handle).Reset(); +#endif + } + + // Fast primitive setters + inline void Set(bool value) { + TYPE_CHECK(T, v8::Boolean); + value_.Set(value); + } + + inline void Set(double i) { + TYPE_CHECK(T, v8::Number); + value_.Set(i); + } + + inline void Set(int32_t i) { + TYPE_CHECK(T, v8::Integer); + value_.Set(i); + } + + inline void Set(uint32_t i) { + TYPE_CHECK(T, v8::Integer); + value_.Set(i); + } + + // Fast JS primitive setters + inline void SetNull() { + TYPE_CHECK(T, v8::Primitive); + value_.SetNull(); + } + + inline void SetUndefined() { + TYPE_CHECK(T, v8::Primitive); + value_.SetUndefined(); + } + + inline void SetEmptyString() { + TYPE_CHECK(T, v8::String); + value_.SetEmptyString(); + } + + // Convenience getter for isolate + inline v8::Isolate *GetIsolate() const { + return value_.GetIsolate(); + } + + // Pointer setter: Uncompilable to prevent inadvertent misuse. + template<typename S> + inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } +}; + +template<typename T> +class FunctionCallbackInfo { + const v8::FunctionCallbackInfo<T> &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline FunctionCallbackInfo( + const v8::FunctionCallbackInfo<T> &info + , v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(info_.GetReturnValue()); + } + + inline v8::Local<v8::Function> Callee() const { return info_.Callee(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + inline bool IsConstructCall() const { return info_.IsConstructCall(); } + inline int Length() const { return info_.Length(); } + inline v8::Local<v8::Value> operator[](int i) const { return info_[i]; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Isolate *GetIsolate() const { return info_.GetIsolate(); } + + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kCalleeIndex = 5; + static const int kContextSaveIndex = 6; + static const int kArgsLength = 7; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) +}; + +template<typename T> +class PropertyCallbackInfo { + const v8::PropertyCallbackInfo<T> &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline PropertyCallbackInfo( + const v8::PropertyCallbackInfo<T> &info + , const v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(info_.GetReturnValue()); + } + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kThisIndex = 5; + static const int kArgsLength = 6; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfo) +}; + +namespace imp { +static +void FunctionCallbackWrapper(const v8::FunctionCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + FunctionCallback callback = reinterpret_cast<FunctionCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value())); + FunctionCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + callback(cbinfo); +} + +typedef void (*NativeFunction)(const v8::FunctionCallbackInfo<v8::Value> &); + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +static +void GetterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativeGetter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void SetterCallbackWrapper( + v8::Local<v8::Name> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<void> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property.As<v8::String>(), value, cbinfo); +} + +typedef void (*NativeSetter)( + v8::Local<v8::Name> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<void> &); +#else +static +void GetterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativeGetter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void SetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<void> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativeSetter)( + v8::Local<v8::String> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<void> &); +#endif + +#if NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +static +void PropertyGetterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativePropertyGetter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertySetterCallbackWrapper( + v8::Local<v8::Name> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), value, cbinfo); +} + +typedef void (*NativePropertySetter)( + v8::Local<v8::Name> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertyEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativePropertyEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void PropertyDeleterCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (NativePropertyDeleter) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void PropertyQueryCallbackWrapper( + v8::Local<v8::Name> property + , const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property.As<v8::String>(), cbinfo); +} + +typedef void (*NativePropertyQuery) + (v8::Local<v8::Name>, const v8::PropertyCallbackInfo<v8::Integer> &); +#else +static +void PropertyGetterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativePropertyGetter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertySetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativePropertySetter)( + v8::Local<v8::String> + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void PropertyEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativePropertyEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void PropertyDeleterCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (NativePropertyDeleter) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void PropertyQueryCallbackWrapper( + v8::Local<v8::String> property + , const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); +} + +typedef void (*NativePropertyQuery) + (v8::Local<v8::String>, const v8::PropertyCallbackInfo<v8::Integer> &); +#endif + +static +void IndexGetterCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexGetter) + (uint32_t, const v8::PropertyCallbackInfo<v8::Value> &); + +static +void IndexSetterCallbackWrapper( + uint32_t index + , v8::Local<v8::Value> value + , const v8::PropertyCallbackInfo<v8::Value> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertySetterIndex) + .As<v8::External>()->Value())); + callback(index, value, cbinfo); +} + +typedef void (*NativeIndexSetter)( + uint32_t + , v8::Local<v8::Value> + , const v8::PropertyCallbackInfo<v8::Value> &); + +static +void IndexEnumeratorCallbackWrapper( + const v8::PropertyCallbackInfo<v8::Array> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField( + kIndexPropertyEnumeratorIndex).As<v8::External>()->Value())); + callback(cbinfo); +} + +typedef void (*NativeIndexEnumerator) + (const v8::PropertyCallbackInfo<v8::Array> &); + +static +void IndexDeleterCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Boolean> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexDeleter) + (uint32_t, const v8::PropertyCallbackInfo<v8::Boolean> &); + +static +void IndexQueryCallbackWrapper( + uint32_t index, const v8::PropertyCallbackInfo<v8::Integer> &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); +} + +typedef void (*NativeIndexQuery) + (uint32_t, const v8::PropertyCallbackInfo<v8::Integer> &); +} // end of namespace imp + +#endif // NAN_CALLBACKS_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..c9ba4993205ec4feed387870b8f33f05e0789f1a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_callbacks_pre_12_inl.h @@ -0,0 +1,520 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CALLBACKS_PRE_12_INL_H_ +#define NAN_CALLBACKS_PRE_12_INL_H_ + +namespace imp { +template<typename T> class ReturnValueImp; +} // end of namespace imp + +template<typename T> +class ReturnValue { + v8::Isolate *isolate_; + v8::Persistent<T> *value_; + friend class imp::ReturnValueImp<T>; + + public: + template <class S> + explicit inline ReturnValue(v8::Isolate *isolate, v8::Persistent<S> *p) : + isolate_(isolate), value_(p) {} + template <class S> + explicit inline ReturnValue(const ReturnValue<S>& that) + : isolate_(that.isolate_), value_(that.value_) { + TYPE_CHECK(T, S); + } + + // Handle setters + template <typename S> inline void Set(const v8::Local<S> &handle) { + TYPE_CHECK(T, S); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(handle); + } + + template <typename S> inline void Set(const Global<S> &handle) { + TYPE_CHECK(T, S); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(handle.persistent); + const_cast<Global<S> &>(handle).Reset(); + } + + // Fast primitive setters + inline void Set(bool value) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Boolean); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Boolean::New(value)); + } + + inline void Set(double i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Number); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Number::New(i)); + } + + inline void Set(int32_t i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Integer); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Int32::New(i)); + } + + inline void Set(uint32_t i) { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Integer); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Uint32::NewFromUnsigned(i)); + } + + // Fast JS primitive setters + inline void SetNull() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Primitive); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Null()); + } + + inline void SetUndefined() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::Primitive); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::Undefined()); + } + + inline void SetEmptyString() { + v8::HandleScope scope; + + TYPE_CHECK(T, v8::String); + value_->Dispose(); + *value_ = v8::Persistent<T>::New(v8::String::Empty()); + } + + // Convenience getter for isolate + inline v8::Isolate *GetIsolate() const { + return isolate_; + } + + // Pointer setter: Uncompilable to prevent inadvertent misuse. + template<typename S> + inline void Set(S *whatever) { TYPE_CHECK(S*, v8::Primitive); } +}; + +template<typename T> +class FunctionCallbackInfo { + const v8::Arguments &args_; + v8::Local<v8::Value> data_; + ReturnValue<T> return_value_; + v8::Persistent<T> retval_; + + public: + explicit inline FunctionCallbackInfo( + const v8::Arguments &args + , v8::Local<v8::Value> data) : + args_(args) + , data_(data) + , return_value_(args.GetIsolate(), &retval_) + , retval_(v8::Persistent<T>::New(v8::Undefined())) {} + + inline ~FunctionCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<T> GetReturnValue() const { + return ReturnValue<T>(return_value_); + } + + inline v8::Local<v8::Function> Callee() const { return args_.Callee(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> Holder() const { return args_.Holder(); } + inline bool IsConstructCall() const { return args_.IsConstructCall(); } + inline int Length() const { return args_.Length(); } + inline v8::Local<v8::Value> operator[](int i) const { return args_[i]; } + inline v8::Local<v8::Object> This() const { return args_.This(); } + inline v8::Isolate *GetIsolate() const { return args_.GetIsolate(); } + + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kCalleeIndex = 5; + static const int kContextSaveIndex = 6; + static const int kArgsLength = 7; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(FunctionCallbackInfo) +}; + +template<typename T> +class PropertyCallbackInfoBase { + const v8::AccessorInfo &info_; + const v8::Local<v8::Value> data_; + + public: + explicit inline PropertyCallbackInfoBase( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + info_(info) + , data_(data) {} + + inline v8::Isolate* GetIsolate() const { return info_.GetIsolate(); } + inline v8::Local<v8::Value> Data() const { return data_; } + inline v8::Local<v8::Object> This() const { return info_.This(); } + inline v8::Local<v8::Object> Holder() const { return info_.Holder(); } + + protected: + static const int kHolderIndex = 0; + static const int kIsolateIndex = 1; + static const int kReturnValueDefaultValueIndex = 2; + static const int kReturnValueIndex = 3; + static const int kDataIndex = 4; + static const int kThisIndex = 5; + static const int kArgsLength = 6; + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(PropertyCallbackInfoBase) +}; + +template<typename T> +class PropertyCallbackInfo : public PropertyCallbackInfoBase<T> { + ReturnValue<T> return_value_; + v8::Persistent<T> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<T>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<T>::New(v8::Undefined())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<T> GetReturnValue() const { return return_value_; } +}; + +template<> +class PropertyCallbackInfo<v8::Array> : + public PropertyCallbackInfoBase<v8::Array> { + ReturnValue<v8::Array> return_value_; + v8::Persistent<v8::Array> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Array>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Array>::New(v8::Local<v8::Array>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Array> GetReturnValue() const { + return return_value_; + } +}; + +template<> +class PropertyCallbackInfo<v8::Boolean> : + public PropertyCallbackInfoBase<v8::Boolean> { + ReturnValue<v8::Boolean> return_value_; + v8::Persistent<v8::Boolean> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Boolean>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Boolean>::New(v8::Local<v8::Boolean>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Boolean> GetReturnValue() const { + return return_value_; + } +}; + +template<> +class PropertyCallbackInfo<v8::Integer> : + public PropertyCallbackInfoBase<v8::Integer> { + ReturnValue<v8::Integer> return_value_; + v8::Persistent<v8::Integer> retval_; + + public: + explicit inline PropertyCallbackInfo( + const v8::AccessorInfo &info + , const v8::Local<v8::Value> data) : + PropertyCallbackInfoBase<v8::Integer>(info, data) + , return_value_(info.GetIsolate(), &retval_) + , retval_(v8::Persistent<v8::Integer>::New(v8::Local<v8::Integer>())) {} + + inline ~PropertyCallbackInfo() { + retval_.Dispose(); + retval_.Clear(); + } + + inline ReturnValue<v8::Integer> GetReturnValue() const { + return return_value_; + } +}; + +namespace imp { +template<typename T> +class ReturnValueImp : public ReturnValue<T> { + public: + explicit ReturnValueImp(ReturnValue<T> that) : + ReturnValue<T>(that) {} + inline v8::Handle<T> Value() { + return *ReturnValue<T>::value_; + } +}; + +static +v8::Handle<v8::Value> FunctionCallbackWrapper(const v8::Arguments &args) { + v8::Local<v8::Object> obj = args.Data().As<v8::Object>(); + FunctionCallback callback = reinterpret_cast<FunctionCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kFunctionIndex).As<v8::External>()->Value())); + FunctionCallbackInfo<v8::Value> + cbinfo(args, obj->GetInternalField(kDataIndex)); + callback(cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeFunction)(const v8::Arguments &); + +static +v8::Handle<v8::Value> GetterCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + GetterCallback callback = reinterpret_cast<GetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kGetterIndex).As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeGetter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +void SetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<void> + cbinfo(info, obj->GetInternalField(kDataIndex)); + SetterCallback callback = reinterpret_cast<SetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kSetterIndex).As<v8::External>()->Value())); + callback(property, value, cbinfo); +} + +typedef void (*NativeSetter) + (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> PropertyGetterCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyGetterCallback callback = reinterpret_cast<PropertyGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativePropertyGetter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> PropertySetterCallbackWrapper( + v8::Local<v8::String> property + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertySetterCallback callback = reinterpret_cast<PropertySetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertySetterIndex) + .As<v8::External>()->Value())); + callback(property, value, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativePropertySetter) + (v8::Local<v8::String>, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Array> PropertyEnumeratorCallbackWrapper( + const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyEnumeratorCallback callback = + reinterpret_cast<PropertyEnumeratorCallback>(reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); + return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Array> (*NativePropertyEnumerator) + (const v8::AccessorInfo &); + +static +v8::Handle<v8::Boolean> PropertyDeleterCallbackWrapper( + v8::Local<v8::String> property + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyDeleterCallback callback = reinterpret_cast<PropertyDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Boolean> (NativePropertyDeleter) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Integer> PropertyQueryCallbackWrapper( + v8::Local<v8::String> property, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + PropertyQueryCallback callback = reinterpret_cast<PropertyQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(property, cbinfo); + return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Integer> (*NativePropertyQuery) + (v8::Local<v8::String>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> IndexGetterCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexGetterCallback callback = reinterpret_cast<IndexGetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyGetterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeIndexGetter) + (uint32_t, const v8::AccessorInfo &); + +static +v8::Handle<v8::Value> IndexSetterCallbackWrapper( + uint32_t index + , v8::Local<v8::Value> value + , const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Value> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexSetterCallback callback = reinterpret_cast<IndexSetterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertySetterIndex) + .As<v8::External>()->Value())); + callback(index, value, cbinfo); + return ReturnValueImp<v8::Value>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Value> (*NativeIndexSetter) + (uint32_t, v8::Local<v8::Value>, const v8::AccessorInfo &); + +static +v8::Handle<v8::Array> IndexEnumeratorCallbackWrapper( + const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Array> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexEnumeratorCallback callback = reinterpret_cast<IndexEnumeratorCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyEnumeratorIndex) + .As<v8::External>()->Value())); + callback(cbinfo); + return ReturnValueImp<v8::Array>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Array> (*NativeIndexEnumerator) + (const v8::AccessorInfo &); + +static +v8::Handle<v8::Boolean> IndexDeleterCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Boolean> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexDeleterCallback callback = reinterpret_cast<IndexDeleterCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyDeleterIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Boolean>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Boolean> (*NativeIndexDeleter) + (uint32_t, const v8::AccessorInfo &); + +static +v8::Handle<v8::Integer> IndexQueryCallbackWrapper( + uint32_t index, const v8::AccessorInfo &info) { + v8::Local<v8::Object> obj = info.Data().As<v8::Object>(); + PropertyCallbackInfo<v8::Integer> + cbinfo(info, obj->GetInternalField(kDataIndex)); + IndexQueryCallback callback = reinterpret_cast<IndexQueryCallback>( + reinterpret_cast<intptr_t>( + obj->GetInternalField(kIndexPropertyQueryIndex) + .As<v8::External>()->Value())); + callback(index, cbinfo); + return ReturnValueImp<v8::Integer>(cbinfo.GetReturnValue()).Value(); +} + +typedef v8::Handle<v8::Integer> (*NativeIndexQuery) + (uint32_t, const v8::AccessorInfo &); +} // end of namespace imp + +#endif // NAN_CALLBACKS_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters.h new file mode 100644 index 0000000000000000000000000000000000000000..c0b327294644045c2c7611d11e1cd83dd3ccab70 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters.h @@ -0,0 +1,72 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_H_ +#define NAN_CONVERTERS_H_ + +namespace imp { +template<typename T> struct ToFactoryBase { + typedef MaybeLocal<T> return_t; +}; +template<typename T> struct ValueFactoryBase { typedef Maybe<T> return_t; }; + +template<typename T> struct ToFactory; + +template<> +struct ToFactory<v8::Function> : ToFactoryBase<v8::Function> { + static inline return_t convert(v8::Local<v8::Value> val) { + if (val.IsEmpty() || !val->IsFunction()) return MaybeLocal<v8::Function>(); + return MaybeLocal<v8::Function>(val.As<v8::Function>()); + } +}; + +#define X(TYPE) \ + template<> \ + struct ToFactory<v8::TYPE> : ToFactoryBase<v8::TYPE> { \ + static inline return_t convert(v8::Local<v8::Value> val); \ + }; + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE) \ + template<> \ + struct ToFactory<TYPE> : ValueFactoryBase<TYPE> { \ + static inline return_t convert(v8::Local<v8::Value> val); \ + }; + +X(bool) +X(double) +X(int64_t) +X(uint32_t) +X(int32_t) + +#undef X +} // end of namespace imp + +template<typename T> +inline +typename imp::ToFactory<T>::return_t To(v8::Local<v8::Value> val) { + return imp::ToFactory<T>::convert(val); +} + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# include "nan_converters_43_inl.h" +#else +# include "nan_converters_pre_43_inl.h" +#endif + +#endif // NAN_CONVERTERS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..742f543279f0e8d30ba54c3538266c161b86cd0f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_43_inl.h @@ -0,0 +1,48 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_43_INL_H_ +#define NAN_CONVERTERS_43_INL_H_ + +#define X(TYPE) \ +imp::ToFactory<v8::TYPE>::return_t \ +imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ + v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ + v8::EscapableHandleScope scope(isolate); \ + return scope.Escape( \ + val->To ## TYPE(isolate->GetCurrentContext()) \ + .FromMaybe(v8::Local<v8::TYPE>())); \ +} + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE, NAME) \ +imp::ToFactory<TYPE>::return_t \ +imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ + v8::Isolate *isolate = v8::Isolate::GetCurrent(); \ + v8::HandleScope scope(isolate); \ + return val->NAME ## Value(isolate->GetCurrentContext()); \ +} + +X(bool, Boolean) +X(double, Number) +X(int64_t, Integer) +X(uint32_t, Uint32) +X(int32_t, Int32) + +#undef X + +#endif // NAN_CONVERTERS_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_pre_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_pre_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..ae0518aa33d0851cd08dfd8a3bb321508e02b64a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_converters_pre_43_inl.h @@ -0,0 +1,42 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_CONVERTERS_PRE_43_INL_H_ +#define NAN_CONVERTERS_PRE_43_INL_H_ + +#define X(TYPE) \ +imp::ToFactory<v8::TYPE>::return_t \ +imp::ToFactory<v8::TYPE>::convert(v8::Local<v8::Value> val) { \ + return val->To ## TYPE(); \ +} + +X(Boolean) +X(Number) +X(String) +X(Object) +X(Integer) +X(Uint32) +X(Int32) + +#undef X + +#define X(TYPE, NAME) \ +imp::ToFactory<TYPE>::return_t \ +imp::ToFactory<TYPE>::convert(v8::Local<v8::Value> val) { \ + return Just(val->NAME ## Value()); \ +} + +X(bool, Boolean) +X(double, Number) +X(int64_t, Integer) +X(uint32_t, Uint32) +X(int32_t, Int32) + +#undef X + +#endif // NAN_CONVERTERS_PRE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_define_own_property_helper.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_define_own_property_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..d710ef2293d93746e87b671e7c5e8577784f9e27 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_define_own_property_helper.h @@ -0,0 +1,29 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_DEFINE_OWN_PROPERTY_HELPER_H_ +#define NAN_DEFINE_OWN_PROPERTY_HELPER_H_ + +namespace imp { + +inline Maybe<bool> DefineOwnPropertyHelper( + v8::PropertyAttribute current + , v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + return !(current & v8::DontDelete) || // configurable OR + (!(current & v8::ReadOnly) && // writable AND + !((attribs ^ current) & ~v8::ReadOnly)) // same excluding RO + ? Just<bool>(obj->ForceSet(key, value, attribs)) + : Nothing<bool>(); +} + +} // end of namespace imp + +#endif // NAN_DEFINE_OWN_PROPERTY_HELPER_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..baacb3801782f2ecdf40f570cece4e6412c3c256 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_12_inl.h @@ -0,0 +1,399 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_12_INL_H_ +#define NAN_IMPLEMENTATION_12_INL_H_ +//============================================================================== +// node v0.11 implementation +//============================================================================== + +namespace imp { + +//=== Array ==================================================================== + +Factory<v8::Array>::return_t +Factory<v8::Array>::New() { + return v8::Array::New(v8::Isolate::GetCurrent()); +} + +Factory<v8::Array>::return_t +Factory<v8::Array>::New(int length) { + return v8::Array::New(v8::Isolate::GetCurrent(), length); +} + +//=== Boolean ================================================================== + +Factory<v8::Boolean>::return_t +Factory<v8::Boolean>::New(bool value) { + return v8::Boolean::New(v8::Isolate::GetCurrent(), value); +} + +//=== Boolean Object =========================================================== + +Factory<v8::BooleanObject>::return_t +Factory<v8::BooleanObject>::New(bool value) { +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + return v8::BooleanObject::New( + v8::Isolate::GetCurrent(), value).As<v8::BooleanObject>(); +#else + return v8::BooleanObject::New(value).As<v8::BooleanObject>(); +#endif +} + +//=== Context ================================================================== + +Factory<v8::Context>::return_t +Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions + , v8::Local<v8::ObjectTemplate> tmpl + , v8::Local<v8::Value> obj) { + return v8::Context::New(v8::Isolate::GetCurrent(), extensions, tmpl, obj); +} + +//=== Date ===================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(v8::Date::New(isolate->GetCurrentContext(), value) + .FromMaybe(v8::Local<v8::Value>()).As<v8::Date>()); +} +#else +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + return v8::Date::New(v8::Isolate::GetCurrent(), value).As<v8::Date>(); +} +#endif + +//=== External ================================================================= + +Factory<v8::External>::return_t +Factory<v8::External>::New(void * value) { + return v8::External::New(v8::Isolate::GetCurrent(), value); +} + +//=== Function ================================================================= + +Factory<v8::Function>::return_t +Factory<v8::Function>::New( FunctionCallback callback + , v8::Local<v8::Value> data) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(isolate, reinterpret_cast<void *>(callback))); + + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + return scope.Escape(v8::Function::New( isolate + , imp::FunctionCallbackWrapper + , obj)); +} + +//=== Function Template ======================================================== + +Factory<v8::FunctionTemplate>::return_t +Factory<v8::FunctionTemplate>::New( FunctionCallback callback + , v8::Local<v8::Value> data + , v8::Local<v8::Signature> signature) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + if (callback) { + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(isolate); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = NewInstance(tpl).ToLocalChecked(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(isolate, reinterpret_cast<void *>(callback))); + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(isolate, data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + return scope.Escape(v8::FunctionTemplate::New( isolate + , imp::FunctionCallbackWrapper + , obj + , signature)); + } else { + return v8::FunctionTemplate::New(isolate, 0, data, signature); + } +} + +//=== Number =================================================================== + +Factory<v8::Number>::return_t +Factory<v8::Number>::New(double value) { + return v8::Number::New(v8::Isolate::GetCurrent(), value); +} + +//=== Number Object ============================================================ + +Factory<v8::NumberObject>::return_t +Factory<v8::NumberObject>::New(double value) { + return v8::NumberObject::New( v8::Isolate::GetCurrent() + , value).As<v8::NumberObject>(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(int32_t value) { + return To<T>(T::New(v8::Isolate::GetCurrent(), value)); +} + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(uint32_t value) { + return To<T>(T::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(int32_t value) { + return To<v8::Uint32>( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(uint32_t value) { + return To<v8::Uint32>( + v8::Uint32::NewFromUnsigned(v8::Isolate::GetCurrent(), value)); +} + +//=== Object =================================================================== + +Factory<v8::Object>::return_t +Factory<v8::Object>::New() { + return v8::Object::New(v8::Isolate::GetCurrent()); +} + +//=== Object Template ========================================================== + +Factory<v8::ObjectTemplate>::return_t +Factory<v8::ObjectTemplate>::New() { + return v8::ObjectTemplate::New(v8::Isolate::GetCurrent()); +} + +//=== RegExp =================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + v8::RegExp::New(isolate->GetCurrentContext(), pattern, flags) + .FromMaybe(v8::Local<v8::RegExp>())); +} +#else +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} +#endif + +//=== Script =================================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source src(source); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) + .FromMaybe(v8::Local<v8::Script>())); +} + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::ScriptCompiler::Source src(source, origin); + return scope.Escape( + v8::ScriptCompiler::Compile(isolate->GetCurrentContext(), &src) + .FromMaybe(v8::Local<v8::Script>())); +} +#else +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::Compile(v8::Isolate::GetCurrent(), &src); +} +#endif + +//=== Signature ================================================================ + +Factory<v8::Signature>::return_t +Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) { + return v8::Signature::New(v8::Isolate::GetCurrent(), receiver); +} + +//=== String =================================================================== + +Factory<v8::String>::return_t +Factory<v8::String>::New() { + return v8::String::Empty(v8::Isolate::GetCurrent()); +} + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::NewFromUtf8( + v8::Isolate::GetCurrent(), value, v8::NewStringType::kNormal, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(std::string const& value) { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), + value.data(), v8::NewStringType::kNormal, static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::NewStringType::kNormal, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternalTwoByte(v8::Isolate::GetCurrent(), value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(ExternalOneByteStringResource * value) { + return v8::String::NewExternalOneByte(v8::Isolate::GetCurrent(), value); +} +#else +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New( + std::string const& value) /* NOLINT(build/include_what_you_use) */ { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::NewFromUtf8(v8::Isolate::GetCurrent(), value.data(), + v8::String::kNormalString, + static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::NewFromTwoByte(v8::Isolate::GetCurrent(), value, + v8::String::kNormalString, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(ExternalOneByteStringResource * value) { + return v8::String::NewExternal(v8::Isolate::GetCurrent(), value); +} +#endif + +//=== String Object ============================================================ + +Factory<v8::StringObject>::return_t +Factory<v8::StringObject>::New(v8::Local<v8::String> value) { + return v8::StringObject::New(value).As<v8::StringObject>(); +} + +//=== Unbound Script =========================================================== + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnboundScript( + v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnboundScript( + v8::Isolate::GetCurrent(), &src); +} +#else +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New(v8::Local<v8::String> source) { + v8::ScriptCompiler::Source src(source); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} + +Factory<v8::UnboundScript>::return_t +Factory<v8::UnboundScript>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + v8::ScriptCompiler::Source src(source, origin); + return v8::ScriptCompiler::CompileUnbound(v8::Isolate::GetCurrent(), &src); +} +#endif + +} // end of namespace imp + +//=== Presistents and Handles ================================================== + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template <typename T> +inline v8::Local<T> New(v8::Handle<T> h) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), h); +} +#endif + +template <typename T, typename M> +inline v8::Local<T> New(v8::Persistent<T, M> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +template <typename T> +inline v8::Local<T> New(Global<T> const& p) { + return v8::Local<T>::New(v8::Isolate::GetCurrent(), p); +} + +#endif // NAN_IMPLEMENTATION_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..1472421afa76883abdc6077d92b7c5d3b6000e77 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_implementation_pre_12_inl.h @@ -0,0 +1,263 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_IMPLEMENTATION_PRE_12_INL_H_ +#define NAN_IMPLEMENTATION_PRE_12_INL_H_ + +//============================================================================== +// node v0.10 implementation +//============================================================================== + +namespace imp { + +//=== Array ==================================================================== + +Factory<v8::Array>::return_t +Factory<v8::Array>::New() { + return v8::Array::New(); +} + +Factory<v8::Array>::return_t +Factory<v8::Array>::New(int length) { + return v8::Array::New(length); +} + +//=== Boolean ================================================================== + +Factory<v8::Boolean>::return_t +Factory<v8::Boolean>::New(bool value) { + return v8::Boolean::New(value)->ToBoolean(); +} + +//=== Boolean Object =========================================================== + +Factory<v8::BooleanObject>::return_t +Factory<v8::BooleanObject>::New(bool value) { + return v8::BooleanObject::New(value).As<v8::BooleanObject>(); +} + +//=== Context ================================================================== + +Factory<v8::Context>::return_t +Factory<v8::Context>::New( v8::ExtensionConfiguration* extensions + , v8::Local<v8::ObjectTemplate> tmpl + , v8::Local<v8::Value> obj) { + v8::Persistent<v8::Context> ctx = v8::Context::New(extensions, tmpl, obj); + v8::Local<v8::Context> lctx = v8::Local<v8::Context>::New(ctx); + ctx.Dispose(); + return lctx; +} + +//=== Date ===================================================================== + +Factory<v8::Date>::return_t +Factory<v8::Date>::New(double value) { + return v8::Date::New(value).As<v8::Date>(); +} + +//=== External ================================================================= + +Factory<v8::External>::return_t +Factory<v8::External>::New(void * value) { + return v8::External::New(value); +} + +//=== Function ================================================================= + +Factory<v8::Function>::return_t +Factory<v8::Function>::New( FunctionCallback callback + , v8::Local<v8::Value> data) { + v8::HandleScope scope; + + return scope.Close(Factory<v8::FunctionTemplate>::New( + callback, data, v8::Local<v8::Signature>()) + ->GetFunction()); +} + + +//=== FunctionTemplate ========================================================= + +Factory<v8::FunctionTemplate>::return_t +Factory<v8::FunctionTemplate>::New( FunctionCallback callback + , v8::Local<v8::Value> data + , v8::Local<v8::Signature> signature) { + if (callback) { + v8::HandleScope scope; + + v8::Local<v8::ObjectTemplate> tpl = v8::ObjectTemplate::New(); + tpl->SetInternalFieldCount(imp::kFunctionFieldCount); + v8::Local<v8::Object> obj = tpl->NewInstance(); + + obj->SetInternalField( + imp::kFunctionIndex + , v8::External::New(reinterpret_cast<void *>(callback))); + + v8::Local<v8::Value> val = v8::Local<v8::Value>::New(data); + + if (!val.IsEmpty()) { + obj->SetInternalField(imp::kDataIndex, val); + } + + // Note(agnat): Emulate length argument here. Unfortunately, I couldn't find + // a way. Have at it though... + return scope.Close( + v8::FunctionTemplate::New(imp::FunctionCallbackWrapper + , obj + , signature)); + } else { + return v8::FunctionTemplate::New(0, data, signature); + } +} + +//=== Number =================================================================== + +Factory<v8::Number>::return_t +Factory<v8::Number>::New(double value) { + return v8::Number::New(value); +} + +//=== Number Object ============================================================ + +Factory<v8::NumberObject>::return_t +Factory<v8::NumberObject>::New(double value) { + return v8::NumberObject::New(value).As<v8::NumberObject>(); +} + +//=== Integer, Int32 and Uint32 ================================================ + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(int32_t value) { + return To<T>(T::New(value)); +} + +template <typename T> +typename IntegerFactory<T>::return_t +IntegerFactory<T>::New(uint32_t value) { + return To<T>(T::NewFromUnsigned(value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(int32_t value) { + return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value)); +} + +Factory<v8::Uint32>::return_t +Factory<v8::Uint32>::New(uint32_t value) { + return To<v8::Uint32>(v8::Uint32::NewFromUnsigned(value)); +} + + +//=== Object =================================================================== + +Factory<v8::Object>::return_t +Factory<v8::Object>::New() { + return v8::Object::New(); +} + +//=== Object Template ========================================================== + +Factory<v8::ObjectTemplate>::return_t +Factory<v8::ObjectTemplate>::New() { + return v8::ObjectTemplate::New(); +} + +//=== RegExp =================================================================== + +Factory<v8::RegExp>::return_t +Factory<v8::RegExp>::New( + v8::Local<v8::String> pattern + , v8::RegExp::Flags flags) { + return v8::RegExp::New(pattern, flags); +} + +//=== Script =================================================================== + +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source) { + return v8::Script::New(source); +} +Factory<v8::Script>::return_t +Factory<v8::Script>::New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin) { + return v8::Script::New(source, const_cast<v8::ScriptOrigin*>(&origin)); +} + +//=== Signature ================================================================ + +Factory<v8::Signature>::return_t +Factory<v8::Signature>::New(Factory<v8::Signature>::FTH receiver) { + return v8::Signature::New(receiver); +} + +//=== String =================================================================== + +Factory<v8::String>::return_t +Factory<v8::String>::New() { + return v8::String::Empty(); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const char * value, int length) { + return v8::String::New(value, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New( + std::string const& value) /* NOLINT(build/include_what_you_use) */ { + assert(value.size() <= INT_MAX && "string too long"); + return v8::String::New(value.data(), static_cast<int>(value.size())); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(const uint16_t * value, int length) { + return v8::String::New(value, length); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalStringResource * value) { + return v8::String::NewExternal(value); +} + +Factory<v8::String>::return_t +Factory<v8::String>::New(v8::String::ExternalAsciiStringResource * value) { + return v8::String::NewExternal(value); +} + +//=== String Object ============================================================ + +Factory<v8::StringObject>::return_t +Factory<v8::StringObject>::New(v8::Local<v8::String> value) { + return v8::StringObject::New(value).As<v8::StringObject>(); +} + +} // end of namespace imp + +//=== Presistents and Handles ================================================== + +template <typename T> +inline v8::Local<T> New(v8::Handle<T> h) { + return v8::Local<T>::New(h); +} + +template <typename T> +inline v8::Local<T> New(v8::Persistent<T> const& p) { + return v8::Local<T>::New(p); +} + +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p) { + return v8::Local<T>::New(p.persistent); +} + +template <typename T> +inline v8::Local<T> New(Global<T> const& p) { + return v8::Local<T>::New(p.persistent); +} + +#endif // NAN_IMPLEMENTATION_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_json.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_json.h new file mode 100644 index 0000000000000000000000000000000000000000..33ac8ba69a082f5be23ce56d4c2d2cc078cd7646 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_json.h @@ -0,0 +1,166 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_JSON_H_ +#define NAN_JSON_H_ + +#if NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION +#define NAN_JSON_H_NEED_PARSE 1 +#else +#define NAN_JSON_H_NEED_PARSE 0 +#endif // NODE_MODULE_VERSION < NODE_0_12_MODULE_VERSION + +#if NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION +#define NAN_JSON_H_NEED_STRINGIFY 0 +#else +#define NAN_JSON_H_NEED_STRINGIFY 1 +#endif // NODE_MODULE_VERSION >= NODE_7_0_MODULE_VERSION + +class JSON { + public: + JSON() { +#if NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY + Nan::HandleScope scope; + + Nan::MaybeLocal<v8::Value> maybe_global_json = Nan::Get( + Nan::GetCurrentContext()->Global(), + Nan::New("JSON").ToLocalChecked() + ); + + assert(!maybe_global_json.IsEmpty() && "global JSON is empty"); + v8::Local<v8::Value> val_global_json = maybe_global_json.ToLocalChecked(); + + assert(val_global_json->IsObject() && "global JSON is not an object"); + Nan::MaybeLocal<v8::Object> maybe_obj_global_json = + Nan::To<v8::Object>(val_global_json); + + assert(!maybe_obj_global_json.IsEmpty() && "global JSON object is empty"); + v8::Local<v8::Object> global_json = maybe_obj_global_json.ToLocalChecked(); + +#if NAN_JSON_H_NEED_PARSE + Nan::MaybeLocal<v8::Value> maybe_parse_method = Nan::Get( + global_json, Nan::New("parse").ToLocalChecked() + ); + + assert(!maybe_parse_method.IsEmpty() && "JSON.parse is empty"); + v8::Local<v8::Value> parse_method = maybe_parse_method.ToLocalChecked(); + + assert(parse_method->IsFunction() && "JSON.parse is not a function"); + parse_cb_.Reset(parse_method.As<v8::Function>()); +#endif // NAN_JSON_H_NEED_PARSE + +#if NAN_JSON_H_NEED_STRINGIFY + Nan::MaybeLocal<v8::Value> maybe_stringify_method = Nan::Get( + global_json, Nan::New("stringify").ToLocalChecked() + ); + + assert(!maybe_stringify_method.IsEmpty() && "JSON.stringify is empty"); + v8::Local<v8::Value> stringify_method = + maybe_stringify_method.ToLocalChecked(); + + assert( + stringify_method->IsFunction() && "JSON.stringify is not a function" + ); + stringify_cb_.Reset(stringify_method.As<v8::Function>()); +#endif // NAN_JSON_H_NEED_STRINGIFY +#endif // NAN_JSON_H_NEED_PARSE + NAN_JSON_H_NEED_STRINGIFY + } + + inline + Nan::MaybeLocal<v8::Value> Parse(v8::Local<v8::String> json_string) { + Nan::EscapableHandleScope scope; +#if NAN_JSON_H_NEED_PARSE + return scope.Escape(parse(json_string)); +#else + Nan::MaybeLocal<v8::Value> result; +#if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && \ + NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION + result = v8::JSON::Parse(json_string); +#else +#if NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION + v8::Local<v8::Context> context_or_isolate = Nan::GetCurrentContext(); +#else + v8::Isolate* context_or_isolate = v8::Isolate::GetCurrent(); +#endif // NODE_MODULE_VERSION > NODE_6_0_MODULE_VERSION + result = v8::JSON::Parse(context_or_isolate, json_string); +#endif // NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION && + // NODE_MODULE_VERSION <= IOJS_2_0_MODULE_VERSION + if (result.IsEmpty()) return v8::Local<v8::Value>(); + return scope.Escape(result.ToLocalChecked()); +#endif // NAN_JSON_H_NEED_PARSE + } + + inline + Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object) { + Nan::EscapableHandleScope scope; + Nan::MaybeLocal<v8::String> result = +#if NAN_JSON_H_NEED_STRINGIFY + Nan::To<v8::String>(stringify(json_object)); +#else + v8::JSON::Stringify(Nan::GetCurrentContext(), json_object); +#endif // NAN_JSON_H_NEED_STRINGIFY + if (result.IsEmpty()) return v8::Local<v8::String>(); + return scope.Escape(result.ToLocalChecked()); + } + + inline + Nan::MaybeLocal<v8::String> Stringify(v8::Local<v8::Object> json_object, + v8::Local<v8::String> gap) { + Nan::EscapableHandleScope scope; + Nan::MaybeLocal<v8::String> result = +#if NAN_JSON_H_NEED_STRINGIFY + Nan::To<v8::String>(stringify(json_object, gap)); +#else + v8::JSON::Stringify(Nan::GetCurrentContext(), json_object, gap); +#endif // NAN_JSON_H_NEED_STRINGIFY + if (result.IsEmpty()) return v8::Local<v8::String>(); + return scope.Escape(result.ToLocalChecked()); + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(JSON) +#if NAN_JSON_H_NEED_PARSE + Nan::Callback parse_cb_; +#endif // NAN_JSON_H_NEED_PARSE +#if NAN_JSON_H_NEED_STRINGIFY + Nan::Callback stringify_cb_; +#endif // NAN_JSON_H_NEED_STRINGIFY + +#if NAN_JSON_H_NEED_PARSE + inline v8::Local<v8::Value> parse(v8::Local<v8::Value> arg) { + assert(!parse_cb_.IsEmpty() && "parse_cb_ is empty"); + AsyncResource resource("nan:JSON.parse"); + return parse_cb_.Call(1, &arg, &resource).FromMaybe(v8::Local<v8::Value>()); + } +#endif // NAN_JSON_H_NEED_PARSE + +#if NAN_JSON_H_NEED_STRINGIFY + inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg) { + assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); + AsyncResource resource("nan:JSON.stringify"); + return stringify_cb_.Call(1, &arg, &resource) + .FromMaybe(v8::Local<v8::Value>()); + } + + inline v8::Local<v8::Value> stringify(v8::Local<v8::Value> arg, + v8::Local<v8::String> gap) { + assert(!stringify_cb_.IsEmpty() && "stringify_cb_ is empty"); + + v8::Local<v8::Value> argv[] = { + arg, + Nan::Null(), + gap + }; + AsyncResource resource("nan:JSON.stringify"); + return stringify_cb_.Call(3, argv, &resource) + .FromMaybe(v8::Local<v8::Value>()); + } +#endif // NAN_JSON_H_NEED_STRINGIFY +}; + +#endif // NAN_JSON_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..91783da65aa9cdcf5dda96668966e6f1b0ce3fbb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_43_inl.h @@ -0,0 +1,369 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_MAYBE_43_INL_H_ +#define NAN_MAYBE_43_INL_H_ + +template<typename T> +using MaybeLocal = v8::MaybeLocal<T>; + +template<typename T> +using Maybe = v8::Maybe<T>; + +template<typename T> +inline Maybe<T> Nothing() { + return v8::Nothing<T>(); +} + +template<typename T> +inline Maybe<T> Just(const T& t) { + return v8::Just<T>(t); +} + +inline +MaybeLocal<v8::String> ToDetailString(v8::Local<v8::Value> val) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(val->ToDetailString(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline +MaybeLocal<v8::Uint32> ToArrayIndex(v8::Local<v8::Value> val) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(val->ToArrayIndex(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Uint32>())); +} + +inline +Maybe<bool> Equals(v8::Local<v8::Value> a, v8::Local<v8::Value>(b)) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return a->Equals(isolate->GetCurrentContext(), b); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Local<v8::Function> h) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Object>())); +} + +inline +MaybeLocal<v8::Object> NewInstance( + v8::Local<v8::Function> h + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext(), argc, argv) + .FromMaybe(v8::Local<v8::Object>())); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Local<v8::ObjectTemplate> h) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(h->NewInstance(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Object>())); +} + + +inline MaybeLocal<v8::Function> GetFunction( + v8::Local<v8::FunctionTemplate> t) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(t->GetFunction(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Function>())); +} + +inline Maybe<bool> Set( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key + , v8::Local<v8::Value> value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Set(isolate->GetCurrentContext(), key, value); +} + +inline Maybe<bool> Set( + v8::Local<v8::Object> obj + , uint32_t index + , v8::Local<v8::Value> value) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Set(isolate->GetCurrentContext(), index, value); +} + +#if NODE_MODULE_VERSION < NODE_4_0_MODULE_VERSION +#include "nan_define_own_property_helper.h" // NOLINT(build/include) +#endif + +inline Maybe<bool> DefineOwnProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key + , v8::Local<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); +#if NODE_MODULE_VERSION >= NODE_4_0_MODULE_VERSION + return obj->DefineOwnProperty(isolate->GetCurrentContext(), key, value, + attribs); +#else + Maybe<v8::PropertyAttribute> maybeCurrent = + obj->GetPropertyAttributes(isolate->GetCurrentContext(), key); + if (maybeCurrent.IsNothing()) { + return Nothing<bool>(); + } + v8::PropertyAttribute current = maybeCurrent.FromJust(); + return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); +#endif +} + +NAN_DEPRECATED inline Maybe<bool> ForceSet( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key + , v8::Local<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); +#if NODE_MODULE_VERSION >= NODE_9_0_MODULE_VERSION + return key->IsName() + ? obj->DefineOwnProperty(isolate->GetCurrentContext(), + key.As<v8::Name>(), value, attribs) + : Nothing<bool>(); +#else + return obj->ForceSet(isolate->GetCurrentContext(), key, value, attribs); +#endif +} + +inline MaybeLocal<v8::Value> Get( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->Get(isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline +MaybeLocal<v8::Value> Get(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->Get(isolate->GetCurrentContext(), index) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline v8::PropertyAttribute GetPropertyAttributes( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->GetPropertyAttributes(isolate->GetCurrentContext(), key) + .FromJust(); +} + +inline Maybe<bool> Has( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Has(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> Has(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Has(isolate->GetCurrentContext(), index); +} + +inline Maybe<bool> Delete( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Delete(isolate->GetCurrentContext(), key); +} + +inline +Maybe<bool> Delete(v8::Local<v8::Object> obj, uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->Delete(isolate->GetCurrentContext(), index); +} + +inline +MaybeLocal<v8::Array> GetPropertyNames(v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetPropertyNames(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Array>())); +} + +inline +MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetOwnPropertyNames(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::Array>())); +} + +inline Maybe<bool> SetPrototype( + v8::Local<v8::Object> obj + , v8::Local<v8::Value> prototype) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->SetPrototype(isolate->GetCurrentContext(), prototype); +} + +inline MaybeLocal<v8::String> ObjectProtoToString( + v8::Local<v8::Object> obj) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->ObjectProtoToString(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline Maybe<bool> HasOwnProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasOwnProperty(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> HasRealNamedProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealNamedProperty(isolate->GetCurrentContext(), key); +} + +inline Maybe<bool> HasRealIndexedProperty( + v8::Local<v8::Object> obj + , uint32_t index) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealIndexedProperty(isolate->GetCurrentContext(), index); +} + +inline Maybe<bool> HasRealNamedCallbackProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return obj->HasRealNamedCallbackProperty(isolate->GetCurrentContext(), key); +} + +inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(obj->GetRealNamedPropertyInPrototypeChain( + isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> GetRealNamedProperty( + v8::Local<v8::Object> obj + , v8::Local<v8::String> key) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->GetRealNamedProperty(isolate->GetCurrentContext(), key) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> CallAsFunction( + v8::Local<v8::Object> obj + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->CallAsFunction(isolate->GetCurrentContext(), recv, argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline MaybeLocal<v8::Value> CallAsConstructor( + v8::Local<v8::Object> obj + , int argc, v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape( + obj->CallAsConstructor(isolate->GetCurrentContext(), argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +inline +MaybeLocal<v8::String> GetSourceLine(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(msg->GetSourceLine(isolate->GetCurrentContext()) + .FromMaybe(v8::Local<v8::String>())); +} + +inline Maybe<int> GetLineNumber(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetLineNumber(isolate->GetCurrentContext()); +} + +inline Maybe<int> GetStartColumn(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetStartColumn(isolate->GetCurrentContext()); +} + +inline Maybe<int> GetEndColumn(v8::Local<v8::Message> msg) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::HandleScope scope(isolate); + return msg->GetEndColumn(isolate->GetCurrentContext()); +} + +inline MaybeLocal<v8::Object> CloneElementAt( + v8::Local<v8::Array> array + , uint32_t index) { +#if (NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION) + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Value> elem; + v8::Local<v8::Object> obj; + if (!array->Get(context, index).ToLocal(&elem)) { + return scope.Escape(obj); + } + if (!elem->ToObject(context).ToLocal(&obj)) { + return scope.Escape(v8::Local<v8::Object>()); + } + return scope.Escape(obj->Clone()); +#else + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(array->CloneElementAt(isolate->GetCurrentContext(), index) + .FromMaybe(v8::Local<v8::Object>())); +#endif +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::Function> fun + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + return scope.Escape(fun->Call(isolate->GetCurrentContext(), recv, argc, argv) + .FromMaybe(v8::Local<v8::Value>())); +} + +#endif // NAN_MAYBE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_pre_43_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_pre_43_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..3847296d5d22d69fa55b21a95033a89aea2802dc --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_maybe_pre_43_inl.h @@ -0,0 +1,316 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_MAYBE_PRE_43_INL_H_ +#define NAN_MAYBE_PRE_43_INL_H_ + +template<typename T> +class MaybeLocal { + public: + inline MaybeLocal() : val_(v8::Local<T>()) {} + + template<typename S> +# if NODE_MODULE_VERSION >= NODE_0_12_MODULE_VERSION + inline + MaybeLocal(v8::Local<S> that) : val_(that) {} // NOLINT(runtime/explicit) +# else + inline + MaybeLocal(v8::Local<S> that) : // NOLINT(runtime/explicit) + val_(*reinterpret_cast<v8::Local<T>*>(&that)) {} +# endif + + inline bool IsEmpty() const { return val_.IsEmpty(); } + + template<typename S> + inline bool ToLocal(v8::Local<S> *out) const { + *out = val_; + return !IsEmpty(); + } + + inline v8::Local<T> ToLocalChecked() const { +#if defined(V8_ENABLE_CHECKS) + assert(!IsEmpty() && "ToLocalChecked is Empty"); +#endif // V8_ENABLE_CHECKS + return val_; + } + + template<typename S> + inline v8::Local<S> FromMaybe(v8::Local<S> default_value) const { + return IsEmpty() ? default_value : v8::Local<S>(val_); + } + + private: + v8::Local<T> val_; +}; + +template<typename T> +class Maybe { + public: + inline bool IsNothing() const { return !has_value_; } + inline bool IsJust() const { return has_value_; } + + inline T FromJust() const { +#if defined(V8_ENABLE_CHECKS) + assert(IsJust() && "FromJust is Nothing"); +#endif // V8_ENABLE_CHECKS + return value_; + } + + inline T FromMaybe(const T& default_value) const { + return has_value_ ? value_ : default_value; + } + + inline bool operator==(const Maybe &other) const { + return (IsJust() == other.IsJust()) && + (!IsJust() || FromJust() == other.FromJust()); + } + + inline bool operator!=(const Maybe &other) const { + return !operator==(other); + } + + private: + Maybe() : has_value_(false) {} + explicit Maybe(const T& t) : has_value_(true), value_(t) {} + bool has_value_; + T value_; + + template<typename U> + friend Maybe<U> Nothing(); + template<typename U> + friend Maybe<U> Just(const U& u); +}; + +template<typename T> +inline Maybe<T> Nothing() { + return Maybe<T>(); +} + +template<typename T> +inline Maybe<T> Just(const T& t) { + return Maybe<T>(t); +} + +inline +MaybeLocal<v8::String> ToDetailString(v8::Handle<v8::Value> val) { + return MaybeLocal<v8::String>(val->ToDetailString()); +} + +inline +MaybeLocal<v8::Uint32> ToArrayIndex(v8::Handle<v8::Value> val) { + return MaybeLocal<v8::Uint32>(val->ToArrayIndex()); +} + +inline +Maybe<bool> Equals(v8::Handle<v8::Value> a, v8::Handle<v8::Value>(b)) { + return Just<bool>(a->Equals(b)); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::Function> h) { + return MaybeLocal<v8::Object>(h->NewInstance()); +} + +inline +MaybeLocal<v8::Object> NewInstance( + v8::Local<v8::Function> h + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Object>(h->NewInstance(argc, argv)); +} + +inline +MaybeLocal<v8::Object> NewInstance(v8::Handle<v8::ObjectTemplate> h) { + return MaybeLocal<v8::Object>(h->NewInstance()); +} + +inline +MaybeLocal<v8::Function> GetFunction(v8::Handle<v8::FunctionTemplate> t) { + return MaybeLocal<v8::Function>(t->GetFunction()); +} + +inline Maybe<bool> Set( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key + , v8::Handle<v8::Value> value) { + return Just<bool>(obj->Set(key, value)); +} + +inline Maybe<bool> Set( + v8::Handle<v8::Object> obj + , uint32_t index + , v8::Handle<v8::Value> value) { + return Just<bool>(obj->Set(index, value)); +} + +#include "nan_define_own_property_helper.h" // NOLINT(build/include) + +inline Maybe<bool> DefineOwnProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + v8::PropertyAttribute current = obj->GetPropertyAttributes(key); + return imp::DefineOwnPropertyHelper(current, obj, key, value, attribs); +} + +NAN_DEPRECATED inline Maybe<bool> ForceSet( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key + , v8::Handle<v8::Value> value + , v8::PropertyAttribute attribs = v8::None) { + return Just<bool>(obj->ForceSet(key, value, attribs)); +} + +inline MaybeLocal<v8::Value> Get( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key) { + return MaybeLocal<v8::Value>(obj->Get(key)); +} + +inline MaybeLocal<v8::Value> Get( + v8::Handle<v8::Object> obj + , uint32_t index) { + return MaybeLocal<v8::Value>(obj->Get(index)); +} + +inline Maybe<v8::PropertyAttribute> GetPropertyAttributes( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> key) { + return Just<v8::PropertyAttribute>(obj->GetPropertyAttributes(key)); +} + +inline Maybe<bool> Has( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->Has(key)); +} + +inline Maybe<bool> Has( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->Has(index)); +} + +inline Maybe<bool> Delete( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->Delete(key)); +} + +inline Maybe<bool> Delete( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->Delete(index)); +} + +inline +MaybeLocal<v8::Array> GetPropertyNames(v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::Array>(obj->GetPropertyNames()); +} + +inline +MaybeLocal<v8::Array> GetOwnPropertyNames(v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::Array>(obj->GetOwnPropertyNames()); +} + +inline Maybe<bool> SetPrototype( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Value> prototype) { + return Just<bool>(obj->SetPrototype(prototype)); +} + +inline MaybeLocal<v8::String> ObjectProtoToString( + v8::Handle<v8::Object> obj) { + return MaybeLocal<v8::String>(obj->ObjectProtoToString()); +} + +inline Maybe<bool> HasOwnProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasOwnProperty(key)); +} + +inline Maybe<bool> HasRealNamedProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasRealNamedProperty(key)); +} + +inline Maybe<bool> HasRealIndexedProperty( + v8::Handle<v8::Object> obj + , uint32_t index) { + return Just<bool>(obj->HasRealIndexedProperty(index)); +} + +inline Maybe<bool> HasRealNamedCallbackProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return Just<bool>(obj->HasRealNamedCallbackProperty(key)); +} + +inline MaybeLocal<v8::Value> GetRealNamedPropertyInPrototypeChain( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return MaybeLocal<v8::Value>( + obj->GetRealNamedPropertyInPrototypeChain(key)); +} + +inline MaybeLocal<v8::Value> GetRealNamedProperty( + v8::Handle<v8::Object> obj + , v8::Handle<v8::String> key) { + return MaybeLocal<v8::Value>(obj->GetRealNamedProperty(key)); +} + +inline MaybeLocal<v8::Value> CallAsFunction( + v8::Handle<v8::Object> obj + , v8::Handle<v8::Object> recv + , int argc + , v8::Handle<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(obj->CallAsFunction(recv, argc, argv)); +} + +inline MaybeLocal<v8::Value> CallAsConstructor( + v8::Handle<v8::Object> obj + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(obj->CallAsConstructor(argc, argv)); +} + +inline +MaybeLocal<v8::String> GetSourceLine(v8::Handle<v8::Message> msg) { + return MaybeLocal<v8::String>(msg->GetSourceLine()); +} + +inline Maybe<int> GetLineNumber(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetLineNumber()); +} + +inline Maybe<int> GetStartColumn(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetStartColumn()); +} + +inline Maybe<int> GetEndColumn(v8::Handle<v8::Message> msg) { + return Just<int>(msg->GetEndColumn()); +} + +inline MaybeLocal<v8::Object> CloneElementAt( + v8::Handle<v8::Array> array + , uint32_t index) { + return MaybeLocal<v8::Object>(array->CloneElementAt(index)); +} + +inline MaybeLocal<v8::Value> Call( + v8::Local<v8::Function> fun + , v8::Local<v8::Object> recv + , int argc + , v8::Local<v8::Value> argv[]) { + return MaybeLocal<v8::Value>(fun->Call(recv, argc, argv)); +} + +#endif // NAN_MAYBE_PRE_43_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_new.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_new.h new file mode 100644 index 0000000000000000000000000000000000000000..cdf8bbe40b9b72c39ee9d4f00bdfc8bb7be6f7f6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_new.h @@ -0,0 +1,340 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_NEW_H_ +#define NAN_NEW_H_ + +namespace imp { // scnr + +// TODO(agnat): Generalize +template <typename T> v8::Local<T> To(v8::Local<v8::Integer> i); + +template <> +inline +v8::Local<v8::Integer> +To<v8::Integer>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Integer>(i).ToLocalChecked(); +} + +template <> +inline +v8::Local<v8::Int32> +To<v8::Int32>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Int32>(i).ToLocalChecked(); +} + +template <> +inline +v8::Local<v8::Uint32> +To<v8::Uint32>(v8::Local<v8::Integer> i) { + return Nan::To<v8::Uint32>(i).ToLocalChecked(); +} + +template <typename T> struct FactoryBase { + typedef v8::Local<T> return_t; +}; + +template <typename T> struct MaybeFactoryBase { + typedef MaybeLocal<T> return_t; +}; + +template <typename T> struct Factory; + +template <> +struct Factory<v8::Array> : FactoryBase<v8::Array> { + static inline return_t New(); + static inline return_t New(int length); +}; + +template <> +struct Factory<v8::Boolean> : FactoryBase<v8::Boolean> { + static inline return_t New(bool value); +}; + +template <> +struct Factory<v8::BooleanObject> : FactoryBase<v8::BooleanObject> { + static inline return_t New(bool value); +}; + +template <> +struct Factory<v8::Context> : FactoryBase<v8::Context> { + static inline + return_t + New( v8::ExtensionConfiguration* extensions = NULL + , v8::Local<v8::ObjectTemplate> tmpl = v8::Local<v8::ObjectTemplate>() + , v8::Local<v8::Value> obj = v8::Local<v8::Value>()); +}; + +template <> +struct Factory<v8::Date> : MaybeFactoryBase<v8::Date> { + static inline return_t New(double value); +}; + +template <> +struct Factory<v8::External> : FactoryBase<v8::External> { + static inline return_t New(void *value); +}; + +template <> +struct Factory<v8::Function> : FactoryBase<v8::Function> { + static inline + return_t + New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()); +}; + +template <> +struct Factory<v8::FunctionTemplate> : FactoryBase<v8::FunctionTemplate> { + static inline + return_t + New( FunctionCallback callback = NULL + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , v8::Local<v8::Signature> signature = v8::Local<v8::Signature>()); +}; + +template <> +struct Factory<v8::Number> : FactoryBase<v8::Number> { + static inline return_t New(double value); +}; + +template <> +struct Factory<v8::NumberObject> : FactoryBase<v8::NumberObject> { + static inline return_t New(double value); +}; + +template <typename T> +struct IntegerFactory : FactoryBase<T> { + typedef typename FactoryBase<T>::return_t return_t; + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory<v8::Integer> : IntegerFactory<v8::Integer> {}; + +template <> +struct Factory<v8::Int32> : IntegerFactory<v8::Int32> {}; + +template <> +struct Factory<v8::Uint32> : FactoryBase<v8::Uint32> { + static inline return_t New(int32_t value); + static inline return_t New(uint32_t value); +}; + +template <> +struct Factory<v8::Object> : FactoryBase<v8::Object> { + static inline return_t New(); +}; + +template <> +struct Factory<v8::ObjectTemplate> : FactoryBase<v8::ObjectTemplate> { + static inline return_t New(); +}; + +template <> +struct Factory<v8::RegExp> : MaybeFactoryBase<v8::RegExp> { + static inline return_t New( + v8::Local<v8::String> pattern, v8::RegExp::Flags flags); +}; + +template <> +struct Factory<v8::Script> : MaybeFactoryBase<v8::Script> { + static inline return_t New( v8::Local<v8::String> source); + static inline return_t New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin); +}; + +template <> +struct Factory<v8::Signature> : FactoryBase<v8::Signature> { + typedef v8::Local<v8::FunctionTemplate> FTH; + static inline return_t New(FTH receiver = FTH()); +}; + +template <> +struct Factory<v8::String> : MaybeFactoryBase<v8::String> { + static inline return_t New(); + static inline return_t New(const char *value, int length = -1); + static inline return_t New(const uint16_t *value, int length = -1); + static inline return_t New(std::string const& value); + + static inline return_t New(v8::String::ExternalStringResource * value); + static inline return_t New(ExternalOneByteStringResource * value); +}; + +template <> +struct Factory<v8::StringObject> : FactoryBase<v8::StringObject> { + static inline return_t New(v8::Local<v8::String> value); +}; + +} // end of namespace imp + +#if (NODE_MODULE_VERSION >= 12) + +namespace imp { + +template <> +struct Factory<v8::UnboundScript> : MaybeFactoryBase<v8::UnboundScript> { + static inline return_t New( v8::Local<v8::String> source); + static inline return_t New( v8::Local<v8::String> source + , v8::ScriptOrigin const& origin); +}; + +} // end of namespace imp + +# include "nan_implementation_12_inl.h" + +#else // NODE_MODULE_VERSION >= 12 + +# include "nan_implementation_pre_12_inl.h" + +#endif + +//=== API ====================================================================== + +template <typename T> +typename imp::Factory<T>::return_t +New() { + return imp::Factory<T>::New(); +} + +template <typename T, typename A0> +typename imp::Factory<T>::return_t +New(A0 arg0) { + return imp::Factory<T>::New(arg0); +} + +template <typename T, typename A0, typename A1> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1) { + return imp::Factory<T>::New(arg0, arg1); +} + +template <typename T, typename A0, typename A1, typename A2> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1, A2 arg2) { + return imp::Factory<T>::New(arg0, arg1, arg2); +} + +template <typename T, typename A0, typename A1, typename A2, typename A3> +typename imp::Factory<T>::return_t +New(A0 arg0, A1 arg1, A2 arg2, A3 arg3) { + return imp::Factory<T>::New(arg0, arg1, arg2, arg3); +} + +// Note(agnat): When passing overloaded function pointers to template functions +// as generic arguments the compiler needs help in picking the right overload. +// These two functions handle New<Function> and New<FunctionTemplate> with +// all argument variations. + +// v8::Function and v8::FunctionTemplate with one or two arguments +template <typename T> +typename imp::Factory<T>::return_t +New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>()) { + return imp::Factory<T>::New(callback, data); +} + +// v8::Function and v8::FunctionTemplate with three arguments +template <typename T, typename A2> +typename imp::Factory<T>::return_t +New( FunctionCallback callback + , v8::Local<v8::Value> data = v8::Local<v8::Value>() + , A2 a2 = A2()) { + return imp::Factory<T>::New(callback, data, a2); +} + +// Convenience + +#if NODE_MODULE_VERSION < IOJS_3_0_MODULE_VERSION +template <typename T> inline v8::Local<T> New(v8::Handle<T> h); +#endif + +#if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +template <typename T, typename M> + inline v8::Local<T> New(v8::Persistent<T, M> const& p); +#else +template <typename T> inline v8::Local<T> New(v8::Persistent<T> const& p); +#endif +template <typename T, typename M> +inline v8::Local<T> New(Persistent<T, M> const& p); +template <typename T> +inline v8::Local<T> New(Global<T> const& p); + +inline +imp::Factory<v8::Boolean>::return_t +New(bool value) { + return New<v8::Boolean>(value); +} + +inline +imp::Factory<v8::Int32>::return_t +New(int32_t value) { + return New<v8::Int32>(value); +} + +inline +imp::Factory<v8::Uint32>::return_t +New(uint32_t value) { + return New<v8::Uint32>(value); +} + +inline +imp::Factory<v8::Number>::return_t +New(double value) { + return New<v8::Number>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(std::string const& value) { // NOLINT(build/include_what_you_use) + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(const char * value, int length) { + return New<v8::String>(value, length); +} + +inline +imp::Factory<v8::String>::return_t +New(const uint16_t * value, int length) { + return New<v8::String>(value, length); +} + +inline +imp::Factory<v8::String>::return_t +New(const char * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(const uint16_t * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(v8::String::ExternalStringResource * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::String>::return_t +New(ExternalOneByteStringResource * value) { + return New<v8::String>(value); +} + +inline +imp::Factory<v8::RegExp>::return_t +New(v8::Local<v8::String> pattern, v8::RegExp::Flags flags) { + return New<v8::RegExp>(pattern, flags); +} + +#endif // NAN_NEW_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_object_wrap.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_object_wrap.h new file mode 100644 index 0000000000000000000000000000000000000000..a4d96178f0b0a2d44a24a5563699795beec18954 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_object_wrap.h @@ -0,0 +1,155 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_OBJECT_WRAP_H_ +#define NAN_OBJECT_WRAP_H_ + +class ObjectWrap { + public: + ObjectWrap() { + refs_ = 0; + } + + + virtual ~ObjectWrap() { + if (persistent().IsEmpty()) { + return; + } + + assert(persistent().IsNearDeath()); + persistent().ClearWeak(); + persistent().Reset(); + } + + + template <class T> + static inline T* Unwrap(v8::Local<v8::Object> object) { + assert(!object.IsEmpty()); + assert(object->InternalFieldCount() > 0); + // Cast to ObjectWrap before casting to T. A direct cast from void + // to T won't work right when T has more than one base class. + void* ptr = GetInternalFieldPointer(object, 0); + ObjectWrap* wrap = static_cast<ObjectWrap*>(ptr); + return static_cast<T*>(wrap); + } + + + inline v8::Local<v8::Object> handle() const { + return New(handle_); + } + + + inline Persistent<v8::Object>& persistent() { + return handle_; + } + + + protected: + inline void Wrap(v8::Local<v8::Object> object) { + assert(persistent().IsEmpty()); + assert(object->InternalFieldCount() > 0); + SetInternalFieldPointer(object, 0, this); + persistent().Reset(object); + MakeWeak(); + } + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + inline void MakeWeak() { + persistent().v8::PersistentBase<v8::Object>::SetWeak( + this, WeakCallback, v8::WeakCallbackType::kParameter); + persistent().MarkIndependent(); + } + +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + + inline void MakeWeak() { + persistent().v8::PersistentBase<v8::Object>::SetWeak(this, WeakCallback); + persistent().MarkIndependent(); + } + +#else + + inline void MakeWeak() { + persistent().persistent.MakeWeak(this, WeakCallback); + persistent().MarkIndependent(); + } + +#endif + + /* Ref() marks the object as being attached to an event loop. + * Refed objects will not be garbage collected, even if + * all references are lost. + */ + virtual void Ref() { + assert(!persistent().IsEmpty()); + persistent().ClearWeak(); + refs_++; + } + + /* Unref() marks an object as detached from the event loop. This is its + * default state. When an object with a "weak" reference changes from + * attached to detached state it will be freed. Be careful not to access + * the object after making this call as it might be gone! + * (A "weak reference" means an object that only has a + * persistant handle.) + * + * DO NOT CALL THIS FROM DESTRUCTOR + */ + virtual void Unref() { + assert(!persistent().IsEmpty()); + assert(!persistent().IsWeak()); + assert(refs_ > 0); + if (--refs_ == 0) + MakeWeak(); + } + + int refs_; // ro + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(ObjectWrap) +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + static void + WeakCallback(v8::WeakCallbackInfo<ObjectWrap> const& info) { + ObjectWrap* wrap = info.GetParameter(); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + + static void + WeakCallback(v8::WeakCallbackData<v8::Object, ObjectWrap> const& data) { + ObjectWrap* wrap = data.GetParameter(); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#else + + static void WeakCallback(v8::Persistent<v8::Value> value, void *data) { + ObjectWrap *wrap = static_cast<ObjectWrap*>(data); + assert(wrap->refs_ == 0); + assert(wrap->handle_.IsNearDeath()); + wrap->handle_.Reset(); + delete wrap; + } + +#endif + Persistent<v8::Object> handle_; +}; + + +#endif // NAN_OBJECT_WRAP_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..d9649e867606c6356e393e9964b5607a08ea4e3a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_12_inl.h @@ -0,0 +1,132 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PERSISTENT_12_INL_H_ +#define NAN_PERSISTENT_12_INL_H_ + +template<typename T, typename M> class Persistent : + public v8::Persistent<T, M> { + public: + inline Persistent() : v8::Persistent<T, M>() {} + + template<typename S> inline Persistent(v8::Local<S> that) : + v8::Persistent<T, M>(v8::Isolate::GetCurrent(), that) {} + + template<typename S, typename M2> + inline + Persistent(const v8::Persistent<S, M2> &that) : // NOLINT(runtime/explicit) + v8::Persistent<T, M2>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type); + + private: + inline T *operator*() const { return *PersistentBase<T>::persistent; } + + template<typename S, typename M2> + inline void Copy(const Persistent<S, M2> &that) { + TYPE_CHECK(T, S); + + this->Reset(); + + if (!that.IsEmpty()) { + this->Reset(that); + M::Copy(that, this); + } + } +}; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +template<typename T> +class Global : public v8::Global<T> { + public: + inline Global() : v8::Global<T>() {} + + template<typename S> inline Global(v8::Local<S> that) : + v8::Global<T>(v8::Isolate::GetCurrent(), that) {} + + template<typename S> + inline + Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) + v8::Global<S>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + reinterpret_cast<Persistent<T>*>(this)->SetWeak( + parameter, callback, type); + } +}; +#else +template<typename T> +class Global : public v8::UniquePersistent<T> { + public: + inline Global() : v8::UniquePersistent<T>() {} + + template<typename S> inline Global(v8::Local<S> that) : + v8::UniquePersistent<T>(v8::Isolate::GetCurrent(), that) {} + + template<typename S> + inline + Global(const v8::PersistentBase<S> &that) : // NOLINT(runtime/explicit) + v8::UniquePersistent<S>(v8::Isolate::GetCurrent(), that) {} + + inline void Reset() { v8::PersistentBase<T>::Reset(); } + + template <typename S> + inline void Reset(const v8::Local<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template <typename S> + inline void Reset(const v8::PersistentBase<S> &other) { + v8::PersistentBase<T>::Reset(v8::Isolate::GetCurrent(), other); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + reinterpret_cast<Persistent<T>*>(this)->SetWeak( + parameter, callback, type); + } +}; +#endif + +#endif // NAN_PERSISTENT_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_pre_12_inl.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_pre_12_inl.h new file mode 100644 index 0000000000000000000000000000000000000000..4c9c59da70b66a8c2090cfefa9078fb886bcf646 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_persistent_pre_12_inl.h @@ -0,0 +1,242 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PERSISTENT_PRE_12_INL_H_ +#define NAN_PERSISTENT_PRE_12_INL_H_ + +template<typename T> +class PersistentBase { + v8::Persistent<T> persistent; + template<typename U> + friend v8::Local<U> New(const PersistentBase<U> &p); + template<typename U, typename M> + friend v8::Local<U> New(const Persistent<U, M> &p); + template<typename U> + friend v8::Local<U> New(const Global<U> &p); + template<typename S> friend class ReturnValue; + + public: + inline PersistentBase() : + persistent() {} + + inline void Reset() { + persistent.Dispose(); + persistent.Clear(); + } + + template<typename S> + inline void Reset(const v8::Local<S> &other) { + TYPE_CHECK(T, S); + + if (!persistent.IsEmpty()) { + persistent.Dispose(); + } + + if (other.IsEmpty()) { + persistent.Clear(); + } else { + persistent = v8::Persistent<T>::New(other); + } + } + + template<typename S> + inline void Reset(const PersistentBase<S> &other) { + TYPE_CHECK(T, S); + + if (!persistent.IsEmpty()) { + persistent.Dispose(); + } + + if (other.IsEmpty()) { + persistent.Clear(); + } else { + persistent = v8::Persistent<T>::New(other.persistent); + } + } + + inline bool IsEmpty() const { return persistent.IsEmpty(); } + + inline void Empty() { persistent.Clear(); } + + template<typename S> + inline bool operator==(const PersistentBase<S> &that) const { + return this->persistent == that.persistent; + } + + template<typename S> + inline bool operator==(const v8::Local<S> &that) const { + return this->persistent == that; + } + + template<typename S> + inline bool operator!=(const PersistentBase<S> &that) const { + return !operator==(that); + } + + template<typename S> + inline bool operator!=(const v8::Local<S> &that) const { + return !operator==(that); + } + + template<typename P> + inline void SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type); + + inline void ClearWeak() { persistent.ClearWeak(); } + + inline void MarkIndependent() { persistent.MarkIndependent(); } + + inline bool IsIndependent() const { return persistent.IsIndependent(); } + + inline bool IsNearDeath() const { return persistent.IsNearDeath(); } + + inline bool IsWeak() const { return persistent.IsWeak(); } + + private: + inline explicit PersistentBase(v8::Persistent<T> that) : + persistent(that) { } + inline explicit PersistentBase(T *val) : persistent(val) {} + template<typename S, typename M> friend class Persistent; + template<typename S> friend class Global; + friend class ObjectWrap; +}; + +template<typename T> +class NonCopyablePersistentTraits { + public: + typedef Persistent<T, NonCopyablePersistentTraits<T> > + NonCopyablePersistent; + static const bool kResetInDestructor = false; + template<typename S, typename M> + inline static void Copy(const Persistent<S, M> &source, + NonCopyablePersistent *dest) { + Uncompilable<v8::Object>(); + } + + template<typename O> inline static void Uncompilable() { + TYPE_CHECK(O, v8::Primitive); + } +}; + +template<typename T> +struct CopyablePersistentTraits { + typedef Persistent<T, CopyablePersistentTraits<T> > CopyablePersistent; + static const bool kResetInDestructor = true; + template<typename S, typename M> + static inline void Copy(const Persistent<S, M> &source, + CopyablePersistent *dest) {} +}; + +template<typename T, typename M> class Persistent : + public PersistentBase<T> { + public: + inline Persistent() {} + + template<typename S> inline Persistent(v8::Handle<S> that) + : PersistentBase<T>(v8::Persistent<T>::New(that)) { + TYPE_CHECK(T, S); + } + + inline Persistent(const Persistent &that) : PersistentBase<T>() { + Copy(that); + } + + template<typename S, typename M2> + inline Persistent(const Persistent<S, M2> &that) : + PersistentBase<T>() { + Copy(that); + } + + inline Persistent &operator=(const Persistent &that) { + Copy(that); + return *this; + } + + template <class S, class M2> + inline Persistent &operator=(const Persistent<S, M2> &that) { + Copy(that); + return *this; + } + + inline ~Persistent() { + if (M::kResetInDestructor) this->Reset(); + } + + private: + inline T *operator*() const { return *PersistentBase<T>::persistent; } + + template<typename S, typename M2> + inline void Copy(const Persistent<S, M2> &that) { + TYPE_CHECK(T, S); + + this->Reset(); + + if (!that.IsEmpty()) { + this->persistent = v8::Persistent<T>::New(that.persistent); + M::Copy(that, this); + } + } +}; + +template<typename T> +class Global : public PersistentBase<T> { + struct RValue { + inline explicit RValue(Global* obj) : object(obj) {} + Global* object; + }; + + public: + inline Global() : PersistentBase<T>(0) { } + + template <typename S> + inline Global(v8::Local<S> that) // NOLINT(runtime/explicit) + : PersistentBase<T>(v8::Persistent<T>::New(that)) { + TYPE_CHECK(T, S); + } + + template <typename S> + inline Global(const PersistentBase<S> &that) // NOLINT(runtime/explicit) + : PersistentBase<T>(that) { + TYPE_CHECK(T, S); + } + /** + * Move constructor. + */ + inline Global(RValue rvalue) // NOLINT(runtime/explicit) + : PersistentBase<T>(rvalue.object->persistent) { + rvalue.object->Reset(); + } + inline ~Global() { this->Reset(); } + /** + * Move via assignment. + */ + template<typename S> + inline Global &operator=(Global<S> rhs) { + TYPE_CHECK(T, S); + this->Reset(rhs.persistent); + rhs.Reset(); + return *this; + } + /** + * Cast operator for moves. + */ + inline operator RValue() { return RValue(this); } + /** + * Pass allows returning uniques from functions, etc. + */ + Global Pass() { return Global(RValue(this)); } + + private: + Global(Global &); + void operator=(Global &); + template<typename S> friend class ReturnValue; +}; + +#endif // NAN_PERSISTENT_PRE_12_INL_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_private.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_private.h new file mode 100644 index 0000000000000000000000000000000000000000..15f44cc8c293861d46c73274e32b910f05011986 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_private.h @@ -0,0 +1,73 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_PRIVATE_H_ +#define NAN_PRIVATE_H_ + +inline Maybe<bool> +HasPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { + HandleScope scope; +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->HasPrivate(context, private_key); +#else + return Just(!object->GetHiddenValue(key).IsEmpty()); +#endif +} + +inline MaybeLocal<v8::Value> +GetPrivate(v8::Local<v8::Object> object, v8::Local<v8::String> key) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::EscapableHandleScope scope(isolate); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + v8::MaybeLocal<v8::Value> v = object->GetPrivate(context, private_key); + return scope.Escape(v.ToLocalChecked()); +#else + EscapableHandleScope scope; + v8::Local<v8::Value> v = object->GetHiddenValue(key); + if (v.IsEmpty()) { + v = Undefined(); + } + return scope.Escape(v); +#endif +} + +inline Maybe<bool> SetPrivate( + v8::Local<v8::Object> object, + v8::Local<v8::String> key, + v8::Local<v8::Value> value) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + HandleScope scope; + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Context> context = isolate->GetCurrentContext(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->SetPrivate(context, private_key, value); +#else + return Just(object->SetHiddenValue(key, value)); +#endif +} + +inline Maybe<bool> DeletePrivate( + v8::Local<v8::Object> object, + v8::Local<v8::String> key) { +#if NODE_MODULE_VERSION >= NODE_6_0_MODULE_VERSION + HandleScope scope; + v8::Isolate *isolate = v8::Isolate::GetCurrent(); + v8::Local<v8::Private> private_key = v8::Private::ForApi(isolate, key); + return object->DeletePrivate(isolate->GetCurrentContext(), private_key); +#else + return Just(object->DeleteHiddenValue(key)); +#endif +} + +#endif // NAN_PRIVATE_H_ + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_string_bytes.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_string_bytes.h new file mode 100644 index 0000000000000000000000000000000000000000..a2e6437d12b74cd29fad17ed6c40e1e739eded2c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_string_bytes.h @@ -0,0 +1,305 @@ +// 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. + +#ifndef NAN_STRING_BYTES_H_ +#define NAN_STRING_BYTES_H_ + +// Decodes a v8::Local<v8::String> or Buffer to a raw char* + +namespace imp { + +using v8::Local; +using v8::Object; +using v8::String; +using v8::Value; + + +//// Base 64 //// + +#define base64_encoded_size(size) ((size + 2 - ((size + 2) % 3)) / 3 * 4) + + + +//// HEX //// + +static bool contains_non_ascii_slow(const char* buf, size_t len) { + for (size_t i = 0; i < len; ++i) { + if (buf[i] & 0x80) return true; + } + return false; +} + + +static bool contains_non_ascii(const char* src, size_t len) { + if (len < 16) { + return contains_non_ascii_slow(src, len); + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned unaligned = reinterpret_cast<uintptr_t>(src) & align_mask; + + if (unaligned > 0) { + const unsigned n = bytes_per_word - unaligned; + if (contains_non_ascii_slow(src, n)) return true; + src += n; + len -= n; + } + + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = 0x8080808080808080ll; +#else + const uintptr_t mask = 0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + if (srcw[i] & mask) return true; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + if (contains_non_ascii_slow(src + offset, remainder)) return true; + } + + return false; +} + + +static void force_ascii_slow(const char* src, char* dst, size_t len) { + for (size_t i = 0; i < len; ++i) { + dst[i] = src[i] & 0x7f; + } +} + + +static void force_ascii(const char* src, char* dst, size_t len) { + if (len < 16) { + force_ascii_slow(src, dst, len); + return; + } + + const unsigned bytes_per_word = sizeof(void*); + const unsigned align_mask = bytes_per_word - 1; + const unsigned src_unalign = reinterpret_cast<uintptr_t>(src) & align_mask; + const unsigned dst_unalign = reinterpret_cast<uintptr_t>(dst) & align_mask; + + if (src_unalign > 0) { + if (src_unalign == dst_unalign) { + const unsigned unalign = bytes_per_word - src_unalign; + force_ascii_slow(src, dst, unalign); + src += unalign; + dst += unalign; + len -= src_unalign; + } else { + force_ascii_slow(src, dst, len); + return; + } + } + +#if defined(__x86_64__) || defined(_WIN64) + const uintptr_t mask = ~0x8080808080808080ll; +#else + const uintptr_t mask = ~0x80808080l; +#endif + + const uintptr_t* srcw = reinterpret_cast<const uintptr_t*>(src); + uintptr_t* dstw = reinterpret_cast<uintptr_t*>(dst); + + for (size_t i = 0, n = len / bytes_per_word; i < n; ++i) { + dstw[i] = srcw[i] & mask; + } + + const unsigned remainder = len & align_mask; + if (remainder > 0) { + const size_t offset = len - remainder; + force_ascii_slow(src + offset, dst + offset, remainder); + } +} + + +static size_t base64_encode(const char* src, + size_t slen, + char* dst, + size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= base64_encoded_size(slen) && + "not enough space provided for base64 encode"); + + dlen = base64_encoded_size(slen); + + unsigned a; + unsigned b; + unsigned c; + unsigned i; + unsigned k; + unsigned n; + + static const char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "abcdefghijklmnopqrstuvwxyz" + "0123456789+/"; + + i = 0; + k = 0; + n = slen / 3 * 3; + + while (i < n) { + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + c = src[i + 2] & 0xff; + + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[((b & 0x0f) << 2) | (c >> 6)]; + dst[k + 3] = table[c & 0x3f]; + + i += 3; + k += 4; + } + + if (n != slen) { + switch (slen - n) { + case 1: + a = src[i + 0] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[(a & 3) << 4]; + dst[k + 2] = '='; + dst[k + 3] = '='; + break; + + case 2: + a = src[i + 0] & 0xff; + b = src[i + 1] & 0xff; + dst[k + 0] = table[a >> 2]; + dst[k + 1] = table[((a & 3) << 4) | (b >> 4)]; + dst[k + 2] = table[(b & 0x0f) << 2]; + dst[k + 3] = '='; + break; + } + } + + return dlen; +} + + +static size_t hex_encode(const char* src, size_t slen, char* dst, size_t dlen) { + // We know how much we'll write, just make sure that there's space. + assert(dlen >= slen * 2 && + "not enough space provided for hex encode"); + + dlen = slen * 2; + for (uint32_t i = 0, k = 0; k < dlen; i += 1, k += 2) { + static const char hex[] = "0123456789abcdef"; + uint8_t val = static_cast<uint8_t>(src[i]); + dst[k + 0] = hex[val >> 4]; + dst[k + 1] = hex[val & 15]; + } + + return dlen; +} + + + +static Local<Value> Encode(const char* buf, + size_t buflen, + enum Encoding encoding) { + assert(buflen <= node::Buffer::kMaxLength); + if (!buflen && encoding != BUFFER) + return New("").ToLocalChecked(); + + Local<String> val; + switch (encoding) { + case BUFFER: + return CopyBuffer(buf, buflen).ToLocalChecked(); + + case ASCII: + if (contains_non_ascii(buf, buflen)) { + char* out = new char[buflen]; + force_ascii(buf, out, buflen); + val = New<String>(out, buflen).ToLocalChecked(); + delete[] out; + } else { + val = New<String>(buf, buflen).ToLocalChecked(); + } + break; + + case UTF8: + val = New<String>(buf, buflen).ToLocalChecked(); + break; + + case BINARY: { + // TODO(isaacs) use ExternalTwoByteString? + const unsigned char *cbuf = reinterpret_cast<const unsigned char*>(buf); + uint16_t * twobytebuf = new uint16_t[buflen]; + for (size_t i = 0; i < buflen; i++) { + // XXX is the following line platform independent? + twobytebuf[i] = cbuf[i]; + } + val = New<String>(twobytebuf, buflen).ToLocalChecked(); + delete[] twobytebuf; + break; + } + + case BASE64: { + size_t dlen = base64_encoded_size(buflen); + char* dst = new char[dlen]; + + size_t written = base64_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = New<String>(dst, dlen).ToLocalChecked(); + delete[] dst; + break; + } + + case UCS2: { + const uint16_t* data = reinterpret_cast<const uint16_t*>(buf); + val = New<String>(data, buflen / 2).ToLocalChecked(); + break; + } + + case HEX: { + size_t dlen = buflen * 2; + char* dst = new char[dlen]; + size_t written = hex_encode(buf, buflen, dst, dlen); + assert(written == dlen); + + val = New<String>(dst, dlen).ToLocalChecked(); + delete[] dst; + break; + } + + default: + assert(0 && "unknown encoding"); + break; + } + + return val; +} + +#undef base64_encoded_size + +} // end of namespace imp + +#endif // NAN_STRING_BYTES_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_typedarray_contents.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_typedarray_contents.h new file mode 100644 index 0000000000000000000000000000000000000000..d28ae323e2276b43733be5cac407fd28b91e55c7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_typedarray_contents.h @@ -0,0 +1,90 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_TYPEDARRAY_CONTENTS_H_ +#define NAN_TYPEDARRAY_CONTENTS_H_ + +template<typename T> +class TypedArrayContents { + public: + inline explicit TypedArrayContents(v8::Local<v8::Value> from) : + length_(0), data_(NULL) { + HandleScope scope; + + size_t length = 0; + void* data = NULL; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + + if (from->IsArrayBufferView()) { + v8::Local<v8::ArrayBufferView> array = + v8::Local<v8::ArrayBufferView>::Cast(from); + + const size_t byte_length = array->ByteLength(); + const ptrdiff_t byte_offset = array->ByteOffset(); + v8::Local<v8::ArrayBuffer> buffer = array->Buffer(); + + length = byte_length / sizeof(T); + data = static_cast<char*>(buffer->GetContents().Data()) + byte_offset; + } + +#else + + if (from->IsObject() && !from->IsNull()) { + v8::Local<v8::Object> array = v8::Local<v8::Object>::Cast(from); + + MaybeLocal<v8::Value> buffer = Get(array, + New<v8::String>("buffer").ToLocalChecked()); + MaybeLocal<v8::Value> byte_length = Get(array, + New<v8::String>("byteLength").ToLocalChecked()); + MaybeLocal<v8::Value> byte_offset = Get(array, + New<v8::String>("byteOffset").ToLocalChecked()); + + if (!buffer.IsEmpty() && + !byte_length.IsEmpty() && byte_length.ToLocalChecked()->IsUint32() && + !byte_offset.IsEmpty() && byte_offset.ToLocalChecked()->IsUint32()) { + data = array->GetIndexedPropertiesExternalArrayData(); + if(data) { + length = byte_length.ToLocalChecked()->Uint32Value() / sizeof(T); + } + } + } + +#endif + +#if defined(_MSC_VER) && _MSC_VER >= 1900 || __cplusplus >= 201103L + assert(reinterpret_cast<uintptr_t>(data) % alignof (T) == 0); +#elif defined(_MSC_VER) && _MSC_VER >= 1600 || defined(__GNUC__) + assert(reinterpret_cast<uintptr_t>(data) % __alignof(T) == 0); +#else + assert(reinterpret_cast<uintptr_t>(data) % sizeof (T) == 0); +#endif + + length_ = length; + data_ = static_cast<T*>(data); + } + + inline size_t length() const { return length_; } + inline T* operator*() { return data_; } + inline const T* operator*() const { return data_; } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(TypedArrayContents) + + //Disable heap allocation + void *operator new(size_t size); + void operator delete(void *, size_t) { + abort(); + } + + size_t length_; + T* data_; +}; + +#endif // NAN_TYPEDARRAY_CONTENTS_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_weak.h b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_weak.h new file mode 100644 index 0000000000000000000000000000000000000000..744ffd6ea0a47bb9b6a01865ee45807d50ca2a1f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/nan_weak.h @@ -0,0 +1,432 @@ +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +#ifndef NAN_WEAK_H_ +#define NAN_WEAK_H_ + +static const int kInternalFieldsInWeakCallback = 2; +static const int kNoInternalFieldIndex = -1; + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::WeakCallbackInfo<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::PhantomCallbackData<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +# define NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ \ + v8::PhantomCallbackData<WeakCallbackInfo<T> > const& +# define NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ \ + v8::InternalFieldsCallbackData<WeakCallbackInfo<T>, void> const& +# define NAN_WEAK_PARAMETER_CALLBACK_SIG_ NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +# define NAN_WEAK_TWOFIELD_CALLBACK_SIG_ NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +# define NAN_WEAK_CALLBACK_DATA_TYPE_ \ + v8::WeakCallbackData<S, WeakCallbackInfo<T> > const& +# define NAN_WEAK_CALLBACK_SIG_ NAN_WEAK_CALLBACK_DATA_TYPE_ +#else +# define NAN_WEAK_CALLBACK_DATA_TYPE_ void * +# define NAN_WEAK_CALLBACK_SIG_ \ + v8::Persistent<v8::Value>, NAN_WEAK_CALLBACK_DATA_TYPE_ +#endif + +template<typename T> +class WeakCallbackInfo { + public: + typedef void (*Callback)(const WeakCallbackInfo<T>& data); + WeakCallbackInfo( + Persistent<v8::Value> *persistent + , Callback callback + , void *parameter + , void *field1 = 0 + , void *field2 = 0) : + callback_(callback), isolate_(0), parameter_(parameter) { + std::memcpy(&persistent_, persistent, sizeof (v8::Persistent<v8::Value>)); + internal_fields_[0] = field1; + internal_fields_[1] = field2; + } + inline v8::Isolate *GetIsolate() const { return isolate_; } + inline T *GetParameter() const { return static_cast<T*>(parameter_); } + inline void *GetInternalField(int index) const { + assert((index == 0 || index == 1) && "internal field index out of bounds"); + if (index == 0) { + return internal_fields_[0]; + } else { + return internal_fields_[1]; + } + } + + private: + NAN_DISALLOW_ASSIGN_COPY_MOVE(WeakCallbackInfo) + Callback callback_; + v8::Isolate *isolate_; + void *parameter_; + void *internal_fields_[kInternalFieldsInWeakCallback]; + v8::Persistent<v8::Value> persistent_; + template<typename S, typename M> friend class Persistent; + template<typename S> friend class PersistentBase; +#if NODE_MODULE_VERSION <= NODE_0_12_MODULE_VERSION +# if NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + template<typename S> + static void invoke(NAN_WEAK_CALLBACK_SIG_ data); + template<typename S> + static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); +# else + static void invoke(NAN_WEAK_CALLBACK_SIG_ data); + static WeakCallbackInfo *unwrap(NAN_WEAK_CALLBACK_DATA_TYPE_ data); +# endif +#else +# if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + template<bool isFirstPass> + static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); + template<bool isFirstPass> + static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); +# else + static void invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data); + static void invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data); +# endif + static WeakCallbackInfo *unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data); + static WeakCallbackInfo *unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data); +#endif +}; + + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) + +template<typename T> +template<bool isFirstPass> +void +WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrapparameter(data); + if (isFirstPass) { + cbinfo->persistent_.Reset(); + data.SetSecondPassCallback(invokeparameter<false>); + } else { + cbinfo->callback_(*cbinfo); + delete cbinfo; + } +} + +template<typename T> +template<bool isFirstPass> +void +WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwraptwofield(data); + if (isFirstPass) { + cbinfo->persistent_.Reset(); + data.SetSecondPassCallback(invoketwofield<false>); + } else { + cbinfo->callback_(*cbinfo); + delete cbinfo; + } +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetParameter()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetInternalField(0)); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ +#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +# elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION + +template<typename T> +void +WeakCallbackInfo<T>::invokeparameter(NAN_WEAK_PARAMETER_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrapparameter(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +void +WeakCallbackInfo<T>::invoketwofield(NAN_WEAK_TWOFIELD_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwraptwofield(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrapparameter( + NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetParameter()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwraptwofield( + NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data.GetInternalField1()); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_PARAMETER_CALLBACK_SIG_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_SIG_ +#undef NAN_WEAK_PARAMETER_CALLBACK_DATA_TYPE_ +#undef NAN_WEAK_TWOFIELD_CALLBACK_DATA_TYPE_ +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION + +template<typename T> +template<typename S> +void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrap(data); + cbinfo->persistent_.Reset(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +template<typename S> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap( + NAN_WEAK_CALLBACK_DATA_TYPE_ data) { + void *parameter = data.GetParameter(); + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(parameter); + cbinfo->isolate_ = data.GetIsolate(); + return cbinfo; +} + +#undef NAN_WEAK_CALLBACK_SIG_ +#undef NAN_WEAK_CALLBACK_DATA_TYPE_ +#else + +template<typename T> +void WeakCallbackInfo<T>::invoke(NAN_WEAK_CALLBACK_SIG_ data) { + WeakCallbackInfo<T> *cbinfo = unwrap(data); + cbinfo->persistent_.Dispose(); + cbinfo->persistent_.Clear(); + cbinfo->callback_(*cbinfo); + delete cbinfo; +} + +template<typename T> +WeakCallbackInfo<T> *WeakCallbackInfo<T>::unwrap( + NAN_WEAK_CALLBACK_DATA_TYPE_ data) { + WeakCallbackInfo<T> *cbinfo = + static_cast<WeakCallbackInfo<T>*>(data); + cbinfo->isolate_ = v8::Isolate::GetCurrent(); + return cbinfo; +} + +#undef NAN_WEAK_CALLBACK_SIG_ +#undef NAN_WEAK_CALLBACK_DATA_TYPE_ +#endif + +#if defined(V8_MAJOR_VERSION) && (V8_MAJOR_VERSION > 4 || \ + (V8_MAJOR_VERSION == 4 && defined(V8_MINOR_VERSION) && V8_MINOR_VERSION >= 3)) +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetWeak( + wcbd + , WeakCallbackInfo<P>::template invokeparameter<true> + , type); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetWeak( + static_cast<WeakCallbackInfo<P>*>(0) + , WeakCallbackInfo<P>::template invoketwofield<true> + , type); + } +} +#elif NODE_MODULE_VERSION > IOJS_1_1_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetPhantom( + wcbd + , WeakCallbackInfo<P>::invokeparameter); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetPhantom( + static_cast<WeakCallbackInfo<P>*>(0) + , WeakCallbackInfo<P>::invoketwofield + , 0 + , count > 1 ? 1 : kNoInternalFieldIndex); + } +} +#elif NODE_MODULE_VERSION > NODE_0_12_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetPhantom( + wcbd + , WeakCallbackInfo<P>::invokeparameter); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + (*self)->SetAlignedPointerInInternalField(0, wcbd); + v8::PersistentBase<T>::SetPhantom( + WeakCallbackInfo<P>::invoketwofield + , 0 + , count > 1 ? 1 : kNoInternalFieldIndex); + } +} +#elif NODE_MODULE_VERSION > NODE_0_10_MODULE_VERSION +template<typename T, typename M> +template<typename P> +inline void Persistent<T, M>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetAlignedPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + v8::PersistentBase<T>::SetWeak(wcbd, WeakCallbackInfo<P>::invoke); + } +} +#else +template<typename T> +template<typename P> +inline void PersistentBase<T>::SetWeak( + P *parameter + , typename WeakCallbackInfo<P>::Callback callback + , WeakCallbackType type) { + WeakCallbackInfo<P> *wcbd; + if (type == WeakCallbackType::kParameter) { + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , parameter); + persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke); + } else { + v8::Local<T>* self = reinterpret_cast<v8::Local<T>*>(this); + assert((*self)->IsObject()); + int count = (*self)->InternalFieldCount(); + void *internal_fields[kInternalFieldsInWeakCallback] = {0, 0}; + for (int i = 0; i < count && i < kInternalFieldsInWeakCallback; i++) { + internal_fields[i] = (*self)->GetPointerFromInternalField(i); + } + wcbd = new WeakCallbackInfo<P>( + reinterpret_cast<Persistent<v8::Value>*>(this) + , callback + , 0 + , internal_fields[0] + , internal_fields[1]); + persistent.MakeWeak(wcbd, WeakCallbackInfo<P>::invoke); + } +} +#endif + +#endif // NAN_WEAK_H_ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/package.json new file mode 100644 index 0000000000000000000000000000000000000000..442fbbf68f6bb09ec7421ccc4bd8a76871e88483 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/package.json @@ -0,0 +1,97 @@ +{ + "_from": "nan@^2.3.3", + "_id": "nan@2.10.0", + "_inBundle": false, + "_integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==", + "_location": "/nan", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "nan@^2.3.3", + "name": "nan", + "escapedName": "nan", + "rawSpec": "^2.3.3", + "saveSpec": null, + "fetchSpec": "^2.3.3" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "_shasum": "96d0cd610ebd58d4b4de9cc0c6828cda99c7548f", + "_spec": "nan@^2.3.3", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "bugs": { + "url": "https://github.com/nodejs/nan/issues" + }, + "bundleDependencies": false, + "contributors": [ + { + "name": "Rod Vagg", + "email": "r@va.gg", + "url": "https://github.com/rvagg" + }, + { + "name": "Benjamin Byholm", + "email": "bbyholm@abo.fi", + "url": "https://github.com/kkoopa/" + }, + { + "name": "Trevor Norris", + "email": "trev.norris@gmail.com", + "url": "https://github.com/trevnorris" + }, + { + "name": "Nathan Rajlich", + "email": "nathan@tootallnate.net", + "url": "https://github.com/TooTallNate" + }, + { + "name": "Brett Lawson", + "email": "brett19@gmail.com", + "url": "https://github.com/brett19" + }, + { + "name": "Ben Noordhuis", + "email": "info@bnoordhuis.nl", + "url": "https://github.com/bnoordhuis" + }, + { + "name": "David Siegel", + "email": "david@artcom.de", + "url": "https://github.com/agnat" + }, + { + "name": "Michael Ira Krufky", + "email": "mkrufky@gmail.com", + "url": "https://github.com/mkrufky" + } + ], + "deprecated": false, + "description": "Native Abstractions for Node.js: C++ header for Node 0.8 -> 9 compatibility", + "devDependencies": { + "bindings": "~1.2.1", + "commander": "^2.8.1", + "glob": "^5.0.14", + "node-gyp": "~3.6.2", + "readable-stream": "^2.1.4", + "request": "=2.81.0", + "tap": "~0.7.1", + "xtend": "~4.0.0" + }, + "homepage": "https://github.com/nodejs/nan#readme", + "license": "MIT", + "main": "include_dirs.js", + "name": "nan", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "scripts": { + "docs": "doc/.build.sh", + "rebuild-tests": "node-gyp rebuild --msvs_version=2015 --directory test", + "test": "tap --gc --stderr test/js/*-test.js" + }, + "version": "2.10.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/1to2.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/1to2.js new file mode 100644 index 0000000000000000000000000000000000000000..337f8bf2c2bed35071f44064780364d66208d5d3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/1to2.js @@ -0,0 +1,412 @@ +#!/usr/bin/env node +/********************************************************************* + * NAN - Native Abstractions for Node.js + * + * Copyright (c) 2018 NAN contributors + * + * MIT License <https://github.com/nodejs/nan/blob/master/LICENSE.md> + ********************************************************************/ + +var commander = require('commander'), + fs = require('fs'), + glob = require('glob'), + groups = [], + total = 0, + warning1 = '/* ERROR: Rewrite using Buffer */\n', + warning2 = '\\/\\* ERROR\\: Rewrite using Buffer \\*\\/\\n', + length, + i; + +fs.readFile(__dirname + '/package.json', 'utf8', function (err, data) { + if (err) { + throw err; + } + + commander + .version(JSON.parse(data).version) + .usage('[options] <file ...>') + .parse(process.argv); + + if (!process.argv.slice(2).length) { + commander.outputHelp(); + } +}); + +/* construct strings representing regular expressions + each expression contains a unique group allowing for identification of the match + the index of this key group, relative to the regular expression in question, + is indicated by the first array member */ + +/* simple substistutions, key group is the entire match, 0 */ +groups.push([0, [ + '_NAN_', + 'NODE_SET_METHOD', + 'NODE_SET_PROTOTYPE_METHOD', + 'NanAsciiString', + 'NanEscapeScope', + 'NanReturnValue', + 'NanUcs2String'].join('|')]); + +/* substitutions of parameterless macros, key group is 1 */ +groups.push([1, ['(', [ + 'NanEscapableScope', + 'NanReturnNull', + 'NanReturnUndefined', + 'NanScope'].join('|'), ')\\(\\)'].join('')]); + +/* replace TryCatch with NanTryCatch once, gobbling possible namespace, key group 2 */ +groups.push([2, '(?:(?:v8\\:\\:)?|(Nan)?)(TryCatch)']); + +/* NanNew("string") will likely not fail a ToLocalChecked(), key group 1 */ +groups.push([1, ['(NanNew)', '(\\("[^\\"]*"[^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); + +/* Removed v8 APIs, warn that the code needs rewriting using node::Buffer, key group 2 */ +groups.push([2, ['(', warning2, ')?', '^.*?(', [ + 'GetIndexedPropertiesExternalArrayDataLength', + 'GetIndexedPropertiesExternalArrayData', + 'GetIndexedPropertiesExternalArrayDataType', + 'GetIndexedPropertiesPixelData', + 'GetIndexedPropertiesPixelDataLength', + 'HasIndexedPropertiesInExternalArrayData', + 'HasIndexedPropertiesInPixelData', + 'SetIndexedPropertiesToExternalArrayData', + 'SetIndexedPropertiesToPixelData'].join('|'), ')'].join('')]); + +/* No need for NanScope in V8-exposed methods, key group 2 */ +groups.push([2, ['((', [ + 'NAN_METHOD', + 'NAN_GETTER', + 'NAN_SETTER', + 'NAN_PROPERTY_GETTER', + 'NAN_PROPERTY_SETTER', + 'NAN_PROPERTY_ENUMERATOR', + 'NAN_PROPERTY_DELETER', + 'NAN_PROPERTY_QUERY', + 'NAN_INDEX_GETTER', + 'NAN_INDEX_SETTER', + 'NAN_INDEX_ENUMERATOR', + 'NAN_INDEX_DELETER', + 'NAN_INDEX_QUERY'].join('|'), ')\\([^\\)]*\\)\\s*\\{)\\s*NanScope\\(\\)\\s*;'].join('')]); + +/* v8::Value::ToXXXXXXX returns v8::MaybeLocal<T>, key group 3 */ +groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->(', [ + 'Boolean', + 'Number', + 'String', + 'Object', + 'Integer', + 'Uint32', + 'Int32'].join('|'), ')\\('].join('')]); + +/* v8::Value::XXXXXXXValue returns v8::Maybe<T>, key group 3 */ +groups.push([3, ['([\\s\\(\\)])([^\\s\\(\\)]+)->((?:', [ + 'Boolean', + 'Number', + 'Integer', + 'Uint32', + 'Int32'].join('|'), ')Value)\\('].join('')]); + +/* NAN_WEAK_CALLBACK macro was removed, write out callback definition, key group 1 */ +groups.push([1, '(NAN_WEAK_CALLBACK)\\(([^\\s\\)]+)\\)']); + +/* node::ObjectWrap and v8::Persistent have been replaced with Nan implementations, key group 1 */ +groups.push([1, ['(', [ + 'NanDisposePersistent', + 'NanObjectWrapHandle'].join('|'), ')\\s*\\(\\s*([^\\s\\)]+)'].join('')]); + +/* Since NanPersistent there is no need for NanMakeWeakPersistent, key group 1 */ +groups.push([1, '(NanMakeWeakPersistent)\\s*\\(\\s*([^\\s,]+)\\s*,\\s*']); + +/* Many methods of v8::Object and others now return v8::MaybeLocal<T>, key group 3 */ +groups.push([3, ['([\\s])([^\\s]+)->(', [ + 'GetEndColumn', + 'GetFunction', + 'GetLineNumber', + 'NewInstance', + 'GetPropertyNames', + 'GetOwnPropertyNames', + 'GetSourceLine', + 'GetStartColumn', + 'ObjectProtoToString', + 'ToArrayIndex', + 'ToDetailString', + 'CallAsConstructor', + 'CallAsFunction', + 'CloneElementAt', + 'Delete', + 'ForceSet', + 'Get', + 'GetPropertyAttributes', + 'GetRealNamedProperty', + 'GetRealNamedPropertyInPrototypeChain', + 'Has', + 'HasOwnProperty', + 'HasRealIndexedProperty', + 'HasRealNamedCallbackProperty', + 'HasRealNamedProperty', + 'Set', + 'SetAccessor', + 'SetIndexedPropertyHandler', + 'SetNamedPropertyHandler', + 'SetPrototype'].join('|'), ')\\('].join('')]); + +/* You should get an error if any of these fail anyways, + or handle the error better, it is indicated either way, key group 2 */ +groups.push([2, ['NanNew(<(?:v8\\:\\:)?(', ['Date', 'String', 'RegExp'].join('|'), ')>)(\\([^\\)]*\\))(?!\\.ToLocalChecked\\(\\))'].join('')]); + +/* v8::Value::Equals now returns a v8::Maybe, key group 3 */ +groups.push([3, '([\\s\\(\\)])([^\\s\\(\\)]+)->(Equals)\\(([^\\s\\)]+)']); + +/* NanPersistent makes this unnecessary, key group 1 */ +groups.push([1, '(NanAssignPersistent)(?:<v8\\:\\:[^>]+>)?\\(([^,]+),\\s*']); + +/* args has been renamed to info, key group 2 */ +groups.push([2, '(\\W)(args)(\\W)']) + +/* node::ObjectWrap was replaced with NanObjectWrap, key group 2 */ +groups.push([2, '(\\W)(?:node\\:\\:)?(ObjectWrap)(\\W)']); + +/* v8::Persistent was replaced with NanPersistent, key group 2 */ +groups.push([2, '(\\W)(?:v8\\:\\:)?(Persistent)(\\W)']); + +/* counts the number of capturing groups in a well-formed regular expression, + ignoring non-capturing groups and escaped parentheses */ +function groupcount(s) { + var positive = s.match(/\((?!\?)/g), + negative = s.match(/\\\(/g); + return (positive ? positive.length : 0) - (negative ? negative.length : 0); +} + +/* compute the absolute position of each key group in the joined master RegExp */ +for (i = 1, length = groups.length; i < length; i++) { + total += groupcount(groups[i - 1][1]); + groups[i][0] += total; +} + +/* create the master RegExp, whis is the union of all the groups' expressions */ +master = new RegExp(groups.map(function (a) { return a[1]; }).join('|'), 'gm'); + +/* replacement function for String.replace, receives 21 arguments */ +function replace() { + /* simple expressions */ + switch (arguments[groups[0][0]]) { + case '_NAN_': + return 'NAN_'; + case 'NODE_SET_METHOD': + return 'NanSetMethod'; + case 'NODE_SET_PROTOTYPE_METHOD': + return 'NanSetPrototypeMethod'; + case 'NanAsciiString': + return 'NanUtf8String'; + case 'NanEscapeScope': + return 'scope.Escape'; + case 'NanReturnNull': + return 'info.GetReturnValue().SetNull'; + case 'NanReturnValue': + return 'info.GetReturnValue().Set'; + case 'NanUcs2String': + return 'v8::String::Value'; + default: + } + + /* macros without arguments */ + switch (arguments[groups[1][0]]) { + case 'NanEscapableScope': + return 'NanEscapableScope scope' + case 'NanReturnUndefined': + return 'return'; + case 'NanScope': + return 'NanScope scope'; + default: + } + + /* TryCatch, emulate negative backref */ + if (arguments[groups[2][0]] === 'TryCatch') { + return arguments[groups[2][0] - 1] ? arguments[0] : 'NanTryCatch'; + } + + /* NanNew("foo") --> NanNew("foo").ToLocalChecked() */ + if (arguments[groups[3][0]] === 'NanNew') { + return [arguments[0], '.ToLocalChecked()'].join(''); + } + + /* insert warning for removed functions as comment on new line above */ + switch (arguments[groups[4][0]]) { + case 'GetIndexedPropertiesExternalArrayData': + case 'GetIndexedPropertiesExternalArrayDataLength': + case 'GetIndexedPropertiesExternalArrayDataType': + case 'GetIndexedPropertiesPixelData': + case 'GetIndexedPropertiesPixelDataLength': + case 'HasIndexedPropertiesInExternalArrayData': + case 'HasIndexedPropertiesInPixelData': + case 'SetIndexedPropertiesToExternalArrayData': + case 'SetIndexedPropertiesToPixelData': + return arguments[groups[4][0] - 1] ? arguments[0] : [warning1, arguments[0]].join(''); + default: + } + + /* remove unnecessary NanScope() */ + switch (arguments[groups[5][0]]) { + case 'NAN_GETTER': + case 'NAN_METHOD': + case 'NAN_SETTER': + case 'NAN_INDEX_DELETER': + case 'NAN_INDEX_ENUMERATOR': + case 'NAN_INDEX_GETTER': + case 'NAN_INDEX_QUERY': + case 'NAN_INDEX_SETTER': + case 'NAN_PROPERTY_DELETER': + case 'NAN_PROPERTY_ENUMERATOR': + case 'NAN_PROPERTY_GETTER': + case 'NAN_PROPERTY_QUERY': + case 'NAN_PROPERTY_SETTER': + return arguments[groups[5][0] - 1]; + default: + } + + /* Value converstion */ + switch (arguments[groups[6][0]]) { + case 'Boolean': + case 'Int32': + case 'Integer': + case 'Number': + case 'Object': + case 'String': + case 'Uint32': + return [arguments[groups[6][0] - 2], 'NanTo<v8::', arguments[groups[6][0]], '>(', arguments[groups[6][0] - 1]].join(''); + default: + } + + /* other value conversion */ + switch (arguments[groups[7][0]]) { + case 'BooleanValue': + return [arguments[groups[7][0] - 2], 'NanTo<bool>(', arguments[groups[7][0] - 1]].join(''); + case 'Int32Value': + return [arguments[groups[7][0] - 2], 'NanTo<int32_t>(', arguments[groups[7][0] - 1]].join(''); + case 'IntegerValue': + return [arguments[groups[7][0] - 2], 'NanTo<int64_t>(', arguments[groups[7][0] - 1]].join(''); + case 'Uint32Value': + return [arguments[groups[7][0] - 2], 'NanTo<uint32_t>(', arguments[groups[7][0] - 1]].join(''); + default: + } + + /* NAN_WEAK_CALLBACK */ + if (arguments[groups[8][0]] === 'NAN_WEAK_CALLBACK') { + return ['template<typename T>\nvoid ', + arguments[groups[8][0] + 1], '(const NanWeakCallbackInfo<T> &data)'].join(''); + } + + /* use methods on NAN classes instead */ + switch (arguments[groups[9][0]]) { + case 'NanDisposePersistent': + return [arguments[groups[9][0] + 1], '.Reset('].join(''); + case 'NanObjectWrapHandle': + return [arguments[groups[9][0] + 1], '->handle('].join(''); + default: + } + + /* use method on NanPersistent instead */ + if (arguments[groups[10][0]] === 'NanMakeWeakPersistent') { + return arguments[groups[10][0] + 1] + '.SetWeak('; + } + + /* These return Maybes, the upper ones take no arguments */ + switch (arguments[groups[11][0]]) { + case 'GetEndColumn': + case 'GetFunction': + case 'GetLineNumber': + case 'GetOwnPropertyNames': + case 'GetPropertyNames': + case 'GetSourceLine': + case 'GetStartColumn': + case 'NewInstance': + case 'ObjectProtoToString': + case 'ToArrayIndex': + case 'ToDetailString': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1]].join(''); + case 'CallAsConstructor': + case 'CallAsFunction': + case 'CloneElementAt': + case 'Delete': + case 'ForceSet': + case 'Get': + case 'GetPropertyAttributes': + case 'GetRealNamedProperty': + case 'GetRealNamedPropertyInPrototypeChain': + case 'Has': + case 'HasOwnProperty': + case 'HasRealIndexedProperty': + case 'HasRealNamedCallbackProperty': + case 'HasRealNamedProperty': + case 'Set': + case 'SetAccessor': + case 'SetIndexedPropertyHandler': + case 'SetNamedPropertyHandler': + case 'SetPrototype': + return [arguments[groups[11][0] - 2], 'Nan', arguments[groups[11][0]], '(', arguments[groups[11][0] - 1], ', '].join(''); + default: + } + + /* Automatic ToLocalChecked(), take it or leave it */ + switch (arguments[groups[12][0]]) { + case 'Date': + case 'String': + case 'RegExp': + return ['NanNew', arguments[groups[12][0] - 1], arguments[groups[12][0] + 1], '.ToLocalChecked()'].join(''); + default: + } + + /* NanEquals is now required for uniformity */ + if (arguments[groups[13][0]] === 'Equals') { + return [arguments[groups[13][0] - 1], 'NanEquals(', arguments[groups[13][0] - 1], ', ', arguments[groups[13][0] + 1]].join(''); + } + + /* use method on replacement class instead */ + if (arguments[groups[14][0]] === 'NanAssignPersistent') { + return [arguments[groups[14][0] + 1], '.Reset('].join(''); + } + + /* args --> info */ + if (arguments[groups[15][0]] === 'args') { + return [arguments[groups[15][0] - 1], 'info', arguments[groups[15][0] + 1]].join(''); + } + + /* ObjectWrap --> NanObjectWrap */ + if (arguments[groups[16][0]] === 'ObjectWrap') { + return [arguments[groups[16][0] - 1], 'NanObjectWrap', arguments[groups[16][0] + 1]].join(''); + } + + /* Persistent --> NanPersistent */ + if (arguments[groups[17][0]] === 'Persistent') { + return [arguments[groups[17][0] - 1], 'NanPersistent', arguments[groups[17][0] + 1]].join(''); + } + + /* This should not happen. A switch is probably missing a case if it does. */ + throw 'Unhandled match: ' + arguments[0]; +} + +/* reads a file, runs replacement and writes it back */ +function processFile(file) { + fs.readFile(file, {encoding: 'utf8'}, function (err, data) { + if (err) { + throw err; + } + + /* run replacement twice, might need more runs */ + fs.writeFile(file, data.replace(master, replace).replace(master, replace), function (err) { + if (err) { + throw err; + } + }); + }); +} + +/* process file names from command line and process the identified files */ +for (i = 2, length = process.argv.length; i < length; i++) { + glob(process.argv[i], function (err, matches) { + if (err) { + throw err; + } + matches.forEach(processFile); + }); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7f07e4b8256dd136943943b575776971c36c25e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/README.md @@ -0,0 +1,14 @@ +1to2 naively converts source code files from NAN 1 to NAN 2. There will be erroneous conversions, +false positives and missed opportunities. The input files are rewritten in place. Make sure that +you have backups. You will have to manually review the changes afterwards and do some touchups. + +```sh +$ tools/1to2.js + + Usage: 1to2 [options] <file ...> + + Options: + + -h, --help output usage information + -V, --version output the version number +``` diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/package.json new file mode 100644 index 0000000000000000000000000000000000000000..2dcdd789394965b8150ff96ead49f1a6ac9caf6a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/nan/tools/package.json @@ -0,0 +1,19 @@ +{ + "name": "1to2", + "version": "1.0.0", + "description": "NAN 1 -> 2 Migration Script", + "main": "1to2.js", + "repository": { + "type": "git", + "url": "git://github.com/nodejs/nan.git" + }, + "contributors": [ + "Benjamin Byholm <bbyholm@abo.fi> (https://github.com/kkoopa/)", + "Mathias Küsel (https://github.com/mathiask88/)" + ], + "dependencies": { + "glob": "~5.0.10", + "commander": "~2.8.1" + }, + "license": "MIT" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.airtap.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.airtap.yml new file mode 100644 index 0000000000000000000000000000000000000000..3417780255e8e2206743100e52bcbb5b66408714 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.airtap.yml @@ -0,0 +1,15 @@ +sauce_connect: true +loopback: airtap.local +browsers: + - name: chrome + version: latest + - name: firefox + version: latest + - name: safari + version: latest + - name: microsoftedge + version: latest + - name: ie + version: latest + - name: iphone + version: latest diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.travis.yml b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.travis.yml new file mode 100644 index 0000000000000000000000000000000000000000..f25afbd2f19c75deaefccf85e63a5181a1fb3e54 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/.travis.yml @@ -0,0 +1,11 @@ +language: node_js +node_js: + - lts/* +addons: + sauce_connect: true + hosts: + - airtap.local +env: + global: + - secure: i51rE9rZGHbcZWlL58j3H1qtL23OIV2r0X4TcQKNI3pw2mubdHFJmfPNNO19ItfReu8wwQMxOehKamwaNvqMiKWyHfn/QcThFQysqzgGZ6AgnUbYx9od6XFNDeWd1sVBf7QBAL07y7KWlYGWCwFwWjabSVySzQhEBdisPcskfkI= + - secure: BKq6/5z9LK3KDkTjs7BGeBZ1KsWgz+MsAXZ4P64NSeVGFaBdXU45+ww1mwxXFt5l22/mhyOQZfebQl+kGVqRSZ+DEgQeCymkNZ6CD8c6w6cLuOJXiXwuu/cDM2DD0tfGeu2YZC7yEikP7BqEFwH3D324rRzSGLF2RSAAwkOI7bE= diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0c068ceecbd48fc4e8279e6451793fec2bf12178 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/README.md new file mode 100644 index 0000000000000000000000000000000000000000..35761fb5f8bbb0728d94496f174dd4c8d4c9e850 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/README.md @@ -0,0 +1,85 @@ +# typedarray-to-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/typedarray-to-buffer/master.svg +[travis-url]: https://travis-ci.org/feross/typedarray-to-buffer +[npm-image]: https://img.shields.io/npm/v/typedarray-to-buffer.svg +[npm-url]: https://npmjs.org/package/typedarray-to-buffer +[downloads-image]: https://img.shields.io/npm/dm/typedarray-to-buffer.svg +[downloads-url]: https://npmjs.org/package/typedarray-to-buffer +[standard-image]: https://img.shields.io/badge/code_style-standard-brightgreen.svg +[standard-url]: https://standardjs.com + +#### Convert a typed array to a [Buffer](https://github.com/feross/buffer) without a copy. + +[![saucelabs][saucelabs-image]][saucelabs-url] + +[saucelabs-image]: https://saucelabs.com/browser-matrix/typedarray-to-buffer.svg +[saucelabs-url]: https://saucelabs.com/u/typedarray-to-buffer + +Say you're using the ['buffer'](https://github.com/feross/buffer) module on npm, or +[browserify](http://browserify.org/) and you're working with lots of binary data. + +Unfortunately, sometimes the browser or someone else's API gives you a typed array like +`Uint8Array` to work with and you need to convert it to a `Buffer`. What do you do? + +Of course: `Buffer.from(uint8array)` + +But, alas, every time you do `Buffer.from(uint8array)` **the entire array gets copied**. +The `Buffer` constructor does a copy; this is +defined by the [node docs](http://nodejs.org/api/buffer.html) and the 'buffer' module +matches the node API exactly. + +So, how can we avoid this expensive copy in +[performance critical applications](https://github.com/feross/buffer/issues/22)? + +***Simply use this module, of course!*** + +If you have an `ArrayBuffer`, you don't need this module, because +`Buffer.from(arrayBuffer)` +[is already efficient](https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length). + +## install + +```bash +npm install typedarray-to-buffer +``` + +## usage + +To convert a typed array to a `Buffer` **without a copy**, do this: + +```js +var toBuffer = require('typedarray-to-buffer') + +var arr = new Uint8Array([1, 2, 3]) +arr = toBuffer(arr) + +// arr is a buffer now! + +arr.toString() // '\u0001\u0002\u0003' +arr.readUInt16BE(0) // 258 +``` + +## how it works + +If the browser supports typed arrays, then `toBuffer` will **augment the typed array** you +pass in with the `Buffer` methods and return it. See [how does Buffer +work?](https://github.com/feross/buffer#how-does-it-work) for more about how augmentation +works. + +This module uses the typed array's underlying `ArrayBuffer` to back the new `Buffer`. This +respects the "view" on the `ArrayBuffer`, i.e. `byteOffset` and `byteLength`. In other +words, if you do `toBuffer(new Uint32Array([1, 2, 3]))`, then the new `Buffer` will +contain `[1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]`, **not** `[1, 2, 3]`. And it still doesn't +require a copy. + +If the browser doesn't support typed arrays, then `toBuffer` will create a new `Buffer` +object, copy the data into it, and return it. There's no simple performance optimization +we can do for old browsers. Oh well. + +If this module is used in node, then it will just call `Buffer.from`. This is just for +the convenience of modules that work in both node and the browser. + +## license + +MIT. Copyright (C) [Feross Aboukhadijeh](http://feross.org). diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/index.js new file mode 100644 index 0000000000000000000000000000000000000000..5fa394dd201d2e717aced4aea51c7a9d81c61361 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/index.js @@ -0,0 +1,25 @@ +/** + * Convert a typed array to a Buffer without a copy + * + * Author: Feross Aboukhadijeh <https://feross.org> + * License: MIT + * + * `npm install typedarray-to-buffer` + */ + +var isTypedArray = require('is-typedarray').strict + +module.exports = function typedarrayToBuffer (arr) { + if (isTypedArray(arr)) { + // To avoid a copy, use the typed array's underlying ArrayBuffer to back new Buffer + var buf = Buffer.from(arr.buffer) + if (arr.byteLength !== arr.buffer.byteLength) { + // Respect the "view", i.e. byteOffset and byteLength, without doing a copy + buf = buf.slice(arr.byteOffset, arr.byteOffset + arr.byteLength) + } + return buf + } else { + // Pass through all other types to `Buffer.from` + return Buffer.from(arr) + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/package.json new file mode 100644 index 0000000000000000000000000000000000000000..66e08c6b7d35c0829dcd2636ebcd6b146552f4e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/package.json @@ -0,0 +1,75 @@ +{ + "_from": "typedarray-to-buffer@^3.1.2", + "_id": "typedarray-to-buffer@3.1.5", + "_inBundle": false, + "_integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "_location": "/typedarray-to-buffer", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "typedarray-to-buffer@^3.1.2", + "name": "typedarray-to-buffer", + "escapedName": "typedarray-to-buffer", + "rawSpec": "^3.1.2", + "saveSpec": null, + "fetchSpec": "^3.1.2" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "_shasum": "a97ee7a9ff42691b9f783ff1bc5112fe3fca9080", + "_spec": "typedarray-to-buffer@^3.1.2", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "Feross Aboukhadijeh", + "email": "feross@feross.org", + "url": "http://feross.org/" + }, + "bugs": { + "url": "https://github.com/feross/typedarray-to-buffer/issues" + }, + "bundleDependencies": false, + "dependencies": { + "is-typedarray": "^1.0.0" + }, + "deprecated": false, + "description": "Convert a typed array to a Buffer without a copy", + "devDependencies": { + "airtap": "0.0.4", + "standard": "*", + "tape": "^4.0.0" + }, + "homepage": "http://feross.org", + "keywords": [ + "buffer", + "typed array", + "convert", + "no copy", + "uint8array", + "uint16array", + "uint32array", + "int16array", + "int32array", + "float32array", + "float64array", + "browser", + "arraybuffer", + "dataview" + ], + "license": "MIT", + "main": "index.js", + "name": "typedarray-to-buffer", + "repository": { + "type": "git", + "url": "git://github.com/feross/typedarray-to-buffer.git" + }, + "scripts": { + "test": "standard && npm run test-node && npm run test-browser", + "test-browser": "airtap -- test/*.js", + "test-browser-local": "airtap --local -- test/*.js", + "test-node": "tape test/*.js" + }, + "version": "3.1.5" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/test/basic.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/test/basic.js new file mode 100644 index 0000000000000000000000000000000000000000..352109682f5c121df3811f202b255d2c9a47294a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/typedarray-to-buffer/test/basic.js @@ -0,0 +1,50 @@ +var test = require('tape') +var toBuffer = require('../') + +test('convert to buffer from Uint8Array', function (t) { + if (typeof Uint8Array !== 'undefined') { + var arr = new Uint8Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 2, 3]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt8(0), 1) + t.equal(arr.readUInt8(1), 2) + t.equal(arr.readUInt8(2), 3) + } else { + t.pass('browser lacks Uint8Array support, skip test') + } + t.end() +}) + +test('convert to buffer from another arrayview type (Uint32Array)', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 1) + t.equal(arr.readUInt32LE(4), 2) + t.equal(arr.readUInt32LE(8), 3) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks Uint32Array support, skip test') + } + t.end() +}) + +test('convert to buffer from ArrayBuffer', function (t) { + if (typeof Uint32Array !== 'undefined' && Buffer.TYPED_ARRAY_SUPPORT !== false) { + var arr = new Uint32Array([1, 2, 3]).subarray(1, 2) + arr = toBuffer(arr) + + t.deepEqual(arr, Buffer.from([2, 0, 0, 0]), 'contents equal') + t.ok(Buffer.isBuffer(arr), 'is buffer') + t.equal(arr.readUInt32LE(0), 2) + t.equal(arr instanceof Uint8Array, true) + } else { + t.pass('browser lacks ArrayBuffer support, skip test') + } + t.end() +}) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/.jshintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..98d8766cb3b3b0fa50480e0e2a8e98e8f351b03b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/.jshintrc @@ -0,0 +1,88 @@ +{ + // JSHint Default Configuration File (as on JSHint website) + // See http://jshint.com/docs/ for more details + + "maxerr" : 50, // {int} Maximum error before stopping + + // Enforcing + "bitwise" : false, // true: Prohibit bitwise operators (&, |, ^, etc.) + "camelcase" : false, // true: Identifiers must be in camelCase + "curly" : true, // true: Require {} for every new block or scope + "eqeqeq" : true, // true: Require triple equals (===) for comparison + "freeze" : true, // true: prohibits overwriting prototypes of native objects such as Array, Date etc. + "forin" : false, // true: Require filtering for..in loops with obj.hasOwnProperty() + "immed" : true, // true: Require immediate invocations to be wrapped in parens e.g. `(function () { } ());` + "latedef" : "nofunc", // true: Require variables/functions to be defined before being used + "newcap" : true, // true: Require capitalization of all constructor functions e.g. `new F()` + "noarg" : true, // true: Prohibit use of `arguments.caller` and `arguments.callee` + "noempty" : true, // true: Prohibit use of empty blocks + "nonbsp" : true, // true: Prohibit "non-breaking whitespace" characters. + "nonew" : true, // true: Prohibit use of constructors for side-effects (without assignment) + "plusplus" : false, // true: Prohibit use of `++` & `--` + "quotmark" : "single", // Quotation mark consistency: + // false : do nothing (default) + // true : ensure whatever is used is consistent + // "single" : require single quotes + // "double" : require double quotes + "undef" : true, // true: Require all non-global variables to be declared (prevents global leaks) + "unused" : "vars", // vars: Require all defined variables be used, ignore function params + "strict" : false, // true: Requires all functions run in ES5 Strict Mode + "maxparams" : false, // {int} Max number of formal params allowed per function + "maxdepth" : false, // {int} Max depth of nested blocks (within functions) + "maxstatements" : false, // {int} Max number statements per function + "maxcomplexity" : false, // {int} Max cyclomatic complexity per function + "maxlen" : false, // {int} Max number of characters per line + + // Relaxing + "asi" : false, // true: Tolerate Automatic Semicolon Insertion (no semicolons) + "boss" : false, // true: Tolerate assignments where comparisons would be expected + "debug" : false, // true: Allow debugger statements e.g. browser breakpoints. + "eqnull" : false, // true: Tolerate use of `== null` + "es5" : false, // true: Allow ES5 syntax (ex: getters and setters) + "esnext" : true, // true: Allow ES.next (ES6) syntax (ex: `const`) + "moz" : false, // true: Allow Mozilla specific syntax (extends and overrides esnext features) + // (ex: `for each`, multiple try/catch, function expression…) + "evil" : false, // true: Tolerate use of `eval` and `new Function()` + "expr" : false, // true: Tolerate `ExpressionStatement` as Programs + "funcscope" : false, // true: Tolerate defining variables inside control statements + "globalstrict" : false, // true: Allow global "use strict" (also enables 'strict') + "iterator" : false, // true: Tolerate using the `__iterator__` property + "lastsemic" : false, // true: Tolerate omitting a semicolon for the last statement of a 1-line block + "laxbreak" : false, // true: Tolerate possibly unsafe line breakings + "laxcomma" : false, // true: Tolerate comma-first style coding + "loopfunc" : false, // true: Tolerate functions being defined in loops + "multistr" : false, // true: Tolerate multi-line strings + "noyield" : false, // true: Tolerate generator functions with no yield statement in them. + "notypeof" : false, // true: Tolerate invalid typeof operator values + "proto" : false, // true: Tolerate using the `__proto__` property + "scripturl" : false, // true: Tolerate script-targeted URLs + "shadow" : false, // true: Allows re-define variables later in code e.g. `var x=1; x=2;` + "sub" : true, // true: Tolerate using `[]` notation when it can still be expressed in dot notation + "supernew" : false, // true: Tolerate `new function () { ... };` and `new Object;` + "validthis" : false, // true: Tolerate using this in a non-constructor function + + // Environments + "browser" : true, // Web Browser (window, document, etc) + "browserify" : true, // Browserify (node.js code in the browser) + "couch" : false, // CouchDB + "devel" : true, // Development/debugging (alert, confirm, etc) + "dojo" : false, // Dojo Toolkit + "jasmine" : false, // Jasmine + "jquery" : false, // jQuery + "mocha" : false, // Mocha + "mootools" : false, // MooTools + "node" : true, // Node.js + "nonstandard" : false, // Widely adopted globals (escape, unescape, etc) + "prototypejs" : false, // Prototype and Scriptaculous + "qunit" : false, // QUnit + "rhino" : false, // Rhino + "shelljs" : false, // ShellJS + "worker" : false, // Web Workers + "wsh" : false, // Windows Scripting Host + "yui" : false, // Yahoo User Interface + + // Custom Globals + "globals" : { // additional predefined global variables + "WebSocket": true + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/CHANGELOG.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/CHANGELOG.md new file mode 100644 index 0000000000000000000000000000000000000000..33655715134a70265d832351fdca360f68aca7d8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/CHANGELOG.md @@ -0,0 +1,225 @@ +Changelog +========= + +Version 1.0.25 +-------------- +*Released 2017-10-18* + +* Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x +* [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml) +* [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil)) +* [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit)) +* [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki)) +* [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker)) + + +Version 1.0.24 +-------------- +*Released 2016-12-28* + +* Fixed a bug when using native keepalive on Node >= 6.0. (Thanks, [@prossin](https://github.com/prossin)) +* Upgrading outdated dependencies + +Version 1.0.23 +-------------- +*Released 2016-05-18* + +* Official support for Node 6.x +* Updating dependencies. Specifically, updating nan to ^2.3.3 + +Version 1.0.22 +-------------- +*Released 2015-09-28* + +* Updating to work with nan 2.x + +Version 1.0.21 +-------------- +*Released 2015-07-22* + +* Incremented and re-published to work around an aborted npm publish of v1.0.20. + +Version 1.0.20 +-------------- +*Released 2015-07-22* + +* Added EventTarget to the W3CWebSocket interface (Thanks, [@ibc](https://github.com/ibc)!) +* Corrected an inaccurate error message. (Thanks, [@lekoaf](https://github.com/lekoaf)!) + +Version 1.0.19 +-------------- +*Released 2015-05-28* + +* Updated to nan v1.8.x (tested with v1.8.4) +* Added `"license": "Apache-2.0"` to package.json via [pull request #199](https://github.com/theturtle32/WebSocket-Node/pull/199) by [@pgilad](https://github.com/pgilad). See [npm1k.org](http://npm1k.org/). + + +Version 1.0.18 +-------------- +*Released 2015-03-19* + +* Resolves [issue #195](https://github.com/theturtle32/WebSocket-Node/pull/179) - passing number to connection.send() causes crash +* [Added close code/reason arguments to W3CWebSocket#close()](https://github.com/theturtle32/WebSocket-Node/issues/184) + + +Version 1.0.17 +-------------- +*Released 2015-01-17* + +* Resolves [issue #179](https://github.com/theturtle32/WebSocket-Node/pull/179) - Allow toBuffer to work with empty data + + +Version 1.0.16 +-------------- +*Released 2015-01-16* + +* Resolves [issue #178](https://github.com/theturtle32/WebSocket-Node/issues/178) - Ping Frames with no data + + +Version 1.0.15 +-------------- +*Released 2015-01-13* + +* Resolves [issue #177](https://github.com/theturtle32/WebSocket-Node/issues/177) - WebSocketClient ignores options unless it has a tlsOptions property + + +Version 1.0.14 +-------------- +*Released 2014-12-03* + +* Resolves [issue #173](https://github.com/theturtle32/WebSocket-Node/issues/173) - To allow the W3CWebSocket interface to accept an optional non-standard configuration object as its third parameter, which will be ignored when running in a browser context. + + +Version 1.0.13 +-------------- +*Released 2014-11-29* + +* Fixes [issue #171](https://github.com/theturtle32/WebSocket-Node/issues/171) - Code to prevent calling req.accept/req.reject multiple times breaks sanity checks in req.accept + + +Version 1.0.12 +-------------- +*Released 2014-11-28* + +* Fixes [issue #170](https://github.com/theturtle32/WebSocket-Node/issues/170) - Non-native XOR implementation broken after making JSHint happy + + +Version 1.0.11 +-------------- +*Released 2014-11-25* + +* Fixes some undefined behavior surrounding closing WebSocket connections and more reliably handles edge cases. +* Adds an implementation of the W3C WebSocket API for browsers to facilitate sharing code between client and server via browserify. (Thanks, [@ibc](https://github.com/ibc)!) +* `WebSocketConnection.prototype.close` now accepts optional `reasonCode` and `description` parameters. +* Calling `accept` or `reject` more than once on a `WebSocketRequest` will now throw an error. [Issue #149](https://github.com/theturtle32/WebSocket-Node/issues/149) +* Handling connections dropped by client before accepted by server [Issue #167](https://github.com/theturtle32/WebSocket-Node/issues/167) +* Integrating Gulp and JSHint (Thanks, [@ibc](https://github.com/ibc)!) +* Starting to add individual unit tests (using substack's [tape](github.com/substack/tape) and [faucet](github.com/substack/faucet)) + + +Version 1.0.10 +-------------- +*Released 2014-10-22* + +* Fixed Issue [#146](https://github.com/theturtle32/WebSocket-Node/issues/146) that was causing WebSocketClient to throw errors when instantiated if passed `tlsOptions`. + +Version 1.0.9 +------------- +*Released 2014-10-20* + +* Fixing an insidious corner-case bug that prevented `WebSocketConnection` from firing the `close` event in certain cases when there was an error on the underlying `Socket`, leading to connections sticking around forever, stuck erroneously in the `connected` state. These "ghost" connections would cause an error event when trying to write to them. +* Removed deprecated `websocketVersion` property. Use `webSocketVersion` instead (case difference). +* Allowing user to specify all properties for `tlsOptions` in WebSocketClient, not just a few whitelisted properties. This keeps us from having to constantly add new config properties for new versions of Node. (Thanks, [jesusprubio](https://github.com/jesusprubio)) +* Removing support for Node 0.4.x and 0.6.x. +* Adding `fuzzingclient.json` spec file for the Autobahn Test Suite. +* Now more fairly emitting `message` events from the `WebSocketConnection`. Previously, all buffered frames for a connection would be processed and all `message` events emitted before moving on to processing the next connection with available data. Now We process one frame per connection (most of the time) in a more fair round-robin fashion. +* Now correctly calling the `EventEmitter` superclass constructor during class instance initialization. +* `WebSocketClient.prototype.connect` now accepts the empty string (`''`) to mean "no subprotocol requested." Previously either `null` or an empty array (`[]`) was required. +* Fixing a `TypeError` bug in `WebSocketRouter` (Thanks, [a0000778](https://github.com/a0000778)) +* Fixing a potential race condition when attaching event listeners to the underlying `Socket`. (Thanks [RichardBsolut](https://github.com/RichardBsolut)) +* `WebSocketClient` now accepts an optional options hash to be passed to `(http|https).request`. (Thanks [mildred](https://github.com/mildred) and [aus](https://github.com/aus)) This enables the following new abilities, amongst others: + * Use WebSocket-Node from behind HTTP/HTTPS proxy servers using [koichik/node-tunnel](https://github.com/koichik/node-tunnel) or similar. + * Specify the local port and local address to bind the outgoing request socket to. +* Adding option to ignore `X-Forwarded-For` headers when accepting connections from untrusted clients. +* Adding ability to mount a `WebSocketServer` instance to an arbitrary number of Node http/https servers. +* Adding browser shim so Browserify won't blow up when trying to package up code that uses WebSocket-Node. The shim is a no-op, it ***does not implement a wrapper*** providing the WebSocket-Node API in the browser. +* Incorporating upstream enhancements for the native C++ UTF-8 validation and xor masking functions. (Thanks [einaros](https://github.com/einaros) and [kkoopa](https://github.com/kkoopa)) + + +Version 1.0.8 +------------- +*Released 2012-12-26* + +* Fixed remaining naming inconsistency of "websocketVersion" as opposed to "webSocketVersion" throughout the code, and added deprecation warnings for use of the old casing throughout. +* Fixed an issue with our case-insensitive handling of WebSocket subprotocols. Clients that requested a mixed-case subprotocol would end up failing the connection when the server accepted the connection, returning a lower-case version of the subprotocol name. Now we return the subprotocol name in the exact casing that was requested by the client, while still maintaining the case-insensitive verification logic for convenience and practicality. +* Making sure that any socket-level activity timeout that may have been set on a TCP socket is removed when initializing a connection. +* Added support for native TCP Keep-Alive instead of using the WebSocket ping/pong packets to serve that function. +* Fixed cookie parsing to be compliant with RFC 2109 + +Version 1.0.7 +------------- +*Released 2012-08-12* + +* ***Native modules are now optional!*** If they fail to compile, WebSocket-Node will still work but will not verify that received UTF-8 data is valid, and xor masking/unmasking of payload data for security purposes will not be as efficient as it is performed in JavaScript instead of native code. +* Reduced Node.JS version requirement back to v0.6.10 + +Version 1.0.6 +------------- +*Released 2012-05-22* + +* Now requires Node v0.6.13 since that's the first version that I can manage to successfully build the native UTF-8 validator with node-gyp through npm. + +Version 1.0.5 +------------- +*Released 2012-05-21* + +* Fixes the issues that users were having building the native UTF-8 validator on Windows platforms. Special Thanks to: + * [zerodivisi0n](https://github.com/zerodivisi0n) + * [andreasbotsikas](https://github.com/andreasbotsikas) +* Fixed accidental global variable usage (Thanks, [hakobera](https://github.com/hakobera)!) +* Added callbacks to the send* methods that provide notification of messages being sent on the wire and any socket errors that may occur when sending a message. (Thanks, [zerodivisi0n](https://github.com/zerodivisi0n)!) +* Added option to disable logging in the echo-server in the test folder (Thanks, [oberstet](https://github.com/oberstet)!) + + +Version 1.0.4 +------------- +*Released 2011-12-18* + +* Now validates that incoming UTF-8 messages do, in fact, contain valid UTF-8 data. The connection is dropped with prejudice if invalid data is received. This strict behavior conforms to the WebSocket RFC and is verified by the Autobahn Test Suite. This is accomplished in a performant way by using a native C++ Node module created by [einaros](https://github.com/einaros). +* Updated handling of connection closure to pass more of the Autobahn Test Suite. + +Version 1.0.3 +------------- +*Released 2011-12-18* + +* Substantial speed increase (~150% on my machine, depending on the circumstances) due to an optimization in FastBufferList.js that drastically reduces the number of memory alloctions and buffer copying. ([kazuyukitanimura](https://github.com/kazuyukitanimura)) + + +Version 1.0.2 +------------- +*Released 2011-11-28* + +* Fixing whiteboard example to work under Node 0.6.x ([theturtle32](https://github.com/theturtle32)) +* Now correctly emitting a `close` event with a 1006 error code if there is a TCP error while writing to the socket during the handshake. ([theturtle32](https://github.com/theturtle32)) +* Catching errors when writing to the TCP socket during the handshake. ([justoneplanet](https://github.com/justoneplanet)) +* No longer outputting console.warn messages when there is an error writing to the TCP socket ([justoneplanet](https://github.com/justoneplanet)) +* Fixing some formatting errors, commas, semicolons, etc. ([kaisellgren](https://github.com/kaisellgren)) + + +Version 1.0.1 +------------- +*Released 2011-11-21* + +* Now works with Node 0.6.2 as well as 0.4.12 +* Support TLS in WebSocketClient +* Added support for setting and reading cookies +* Added WebSocketServer.prototype.broadcast(data) convenience method +* Added `resourceURL` property to WebSocketRequest objects. It is a Node URL object with the `resource` and any query string params already parsed. +* The WebSocket request router no longer includes the entire query string when trying to match the path name of the request. +* WebSocketRouterRequest objects now include all the properties and events of WebSocketRequest objects. +* Removed more console.log statements. Please rely on the various events emitted to be notified of error conditions. I decided that it is not a library's place to spew information to the console. +* Renamed the `websocketVersion` property to `webSocketVersion` throughout the code to fix inconsistent capitalization. `websocketVersion` has been kept for compatibility but is deprecated and may be removed in the future. +* Now outputting the sanitized version of custom header names rather than the raw value. This prevents invalid HTTP from being put onto the wire if given an illegal header name. + + +I decided it's time to start maintaining a changelog now, starting with version 1.0.1. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..430d42bbea592e3c130eda0a07a7e1082b96ba73 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/LICENSE @@ -0,0 +1,177 @@ + + 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 diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..39ff64556ce65f5fe7749e2f07c9476e281a0663 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/Makefile @@ -0,0 +1,11 @@ +all: + node-gyp configure build + +clean: + node-gyp clean + +autobahn: + @NODE_PATH=lib node test/autobahn-test-client.js --host=127.0.0.1 --port=9000 + +autobahn-server: + @NODE_PATH=lib node test/echo-server.js diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/README.md new file mode 100644 index 0000000000000000000000000000000000000000..df9584f7d536f63fe3276b5845fad700ffa46e25 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/README.md @@ -0,0 +1,291 @@ +WebSocket Client & Server Implementation for Node +================================================= + +[](http://badge.fury.io/js/websocket) + +[](https://www.npmjs.com/package/websocket) + +[](https://nodei.co/npm/websocket/) + +[](https://nodei.co/npm/websocket/) + +[ ](https://codeship.com/projects/61106) + +Overview +-------- +This is a (mostly) pure JavaScript implementation of the WebSocket protocol versions 8 and 13 for Node. There are some example client and server applications that implement various interoperability testing protocols in the "test/scripts" folder. + +For a WebSocket client written in ActionScript 3, see my [AS3WebScocket](https://github.com/theturtle32/AS3WebSocket) project. + + +Documentation +============= + +[You can read the full API documentation in the docs folder.](docs/index.md) + + +Changelog +--------- + +***Current Version: 1.0.25*** — Released 2017-10-18 + +* Bumping minimum supported node version specified in package.json to v0.10.x because some upstream libraries no longer install on v0.8.x +* [Allowing use of close codes 1012, 1013, 1014](https://www.iana.org/assignments/websocket/websocket.xml) +* [Allowing the `Host` header to be overridden.](https://github.com/theturtle32/WebSocket-Node/pull/291) (Thanks, [@Juneil](https://github.com/Juneil)) +* [Mitigating infinite loop for broken connections](https://github.com/theturtle32/WebSocket-Node/pull/289) (Thanks, [@tvkit](https://github.com/tvkit)) +* [Fixed Markdown Typos](https://github.com/theturtle32/WebSocket-Node/pull/281) (Thanks, [@teramotodaiki](https://github.com/teramotodaiki)) +* [Adding old readyState constants for W3CWebSocket interface](https://github.com/theturtle32/WebSocket-Node/pull/282) (Thanks, [@thechriswalker](https://github.com/thechriswalker)) + +[View the full changelog](CHANGELOG.md) + +Browser Support +--------------- + +All current browsers are fully supported. + +* Firefox 7-9 (Old) (Protocol Version 8) +* Firefox 10+ (Protocol Version 13) +* Chrome 14,15 (Old) (Protocol Version 8) +* Chrome 16+ (Protocol Version 13) +* Internet Explorer 10+ (Protocol Version 13) +* Safari 6+ (Protocol Version 13) + +***Safari older than 6.0 is not supported since it uses a very old draft of WebSockets*** + +***If you need to simultaneously support legacy browser versions that had implemented draft-75/draft-76/draft-00, take a look here: https://gist.github.com/1428579*** + +Benchmarks +---------- +There are some basic benchmarking sections in the Autobahn test suite. I've put up a [benchmark page](http://theturtle32.github.com/WebSocket-Node/benchmarks/) that shows the results from the Autobahn tests run against AutobahnServer 0.4.10, WebSocket-Node 1.0.2, WebSocket-Node 1.0.4, and ws 0.3.4. + +Autobahn Tests +-------------- +The very complete [Autobahn Test Suite](http://autobahn.ws/testsuite/) is used by most WebSocket implementations to test spec compliance and interoperability. + +- [View Server Test Results](http://theturtle32.github.com/WebSocket-Node/test-report/servers/) + +Notes +----- +This library has been used in production on [worlize.com](https://www.worlize.com) since April 2011 and seems to be stable. Your mileage may vary. + +**Tested with the following node versions:** + +- 6.2.0 +- 5.11.1 +- 4.4.4 +- 0.10.45 + +It may work in earlier or later versions but I'm not actively testing it outside of the listed versions. YMMV. + +Installation +------------ + +A few users have reported difficulties building the native extensions without first manually installing node-gyp. If you have trouble building the native extensions, make sure you've got a C++ compiler, and have done `npm install -g node-gyp` first. + +Native extensions are optional, however, and WebSocket-Node will work even if the extensions cannot be compiled. + +In your project root: + + $ npm install websocket + +Then in your code: + +```javascript +var WebSocketServer = require('websocket').server; +var WebSocketClient = require('websocket').client; +var WebSocketFrame = require('websocket').frame; +var WebSocketRouter = require('websocket').router; +var W3CWebSocket = require('websocket').w3cwebsocket; +``` + +Note for Windows Users +---------------------- +Because there is a small C++ component used for validating UTF-8 data, you will need to install a few other software packages in addition to Node to be able to build this module: + +- [Microsoft Visual C++](http://www.microsoft.com/visualstudio/en-us/products/2010-editions/visual-cpp-express) +- [Python 2.7](http://www.python.org/download/) (NOT Python 3.x) + + +Current Features: +----------------- +- Licensed under the Apache License, Version 2.0 +- Protocol version "8" and "13" (Draft-08 through the final RFC) framing and handshake +- Can handle/aggregate received fragmented messages +- Can fragment outgoing messages +- Router to mount multiple applications to various path and protocol combinations +- TLS supported for outbound connections via WebSocketClient +- TLS supported for server connections (use https.createServer instead of http.createServer) + - Thanks to [pors](https://github.com/pors) for confirming this! +- Cookie setting and parsing +- Tunable settings + - Max Receivable Frame Size + - Max Aggregate ReceivedMessage Size + - Whether to fragment outgoing messages + - Fragmentation chunk size for outgoing messages + - Whether to automatically send ping frames for the purposes of keepalive + - Keep-alive ping interval + - Whether or not to automatically assemble received fragments (allows application to handle individual fragments directly) + - How long to wait after sending a close frame for acknowledgment before closing the socket. +- [W3C WebSocket API](http://www.w3.org/TR/websockets/) for applications running on both Node and browsers (via the `W3CWebSocket` class). + + +Known Issues/Missing Features: +------------------------------ +- No API for user-provided protocol extensions. + + +Usage Examples +============== + +Server Example +-------------- + +Here's a short example showing a server that echos back anything sent to it, whether utf-8 or binary. + +```javascript +#!/usr/bin/env node +var WebSocketServer = require('websocket').server; +var http = require('http'); + +var server = http.createServer(function(request, response) { + console.log((new Date()) + ' Received request for ' + request.url); + response.writeHead(404); + response.end(); +}); +server.listen(8080, function() { + console.log((new Date()) + ' Server is listening on port 8080'); +}); + +wsServer = new WebSocketServer({ + httpServer: server, + // You should not use autoAcceptConnections for production + // applications, as it defeats all standard cross-origin protection + // facilities built into the protocol and the browser. You should + // *always* verify the connection's origin and decide whether or not + // to accept it. + autoAcceptConnections: false +}); + +function originIsAllowed(origin) { + // put logic here to detect whether the specified origin is allowed. + return true; +} + +wsServer.on('request', function(request) { + if (!originIsAllowed(request.origin)) { + // Make sure we only accept requests from an allowed origin + request.reject(); + console.log((new Date()) + ' Connection from origin ' + request.origin + ' rejected.'); + return; + } + + var connection = request.accept('echo-protocol', request.origin); + console.log((new Date()) + ' Connection accepted.'); + connection.on('message', function(message) { + if (message.type === 'utf8') { + console.log('Received Message: ' + message.utf8Data); + connection.sendUTF(message.utf8Data); + } + else if (message.type === 'binary') { + console.log('Received Binary Message of ' + message.binaryData.length + ' bytes'); + connection.sendBytes(message.binaryData); + } + }); + connection.on('close', function(reasonCode, description) { + console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.'); + }); +}); +``` + +Client Example +-------------- + +This is a simple example client that will print out any utf-8 messages it receives on the console, and periodically sends a random number. + +*This code demonstrates a client in Node.js, not in the browser* + +```javascript +#!/usr/bin/env node +var WebSocketClient = require('websocket').client; + +var client = new WebSocketClient(); + +client.on('connectFailed', function(error) { + console.log('Connect Error: ' + error.toString()); +}); + +client.on('connect', function(connection) { + console.log('WebSocket Client Connected'); + connection.on('error', function(error) { + console.log("Connection Error: " + error.toString()); + }); + connection.on('close', function() { + console.log('echo-protocol Connection Closed'); + }); + connection.on('message', function(message) { + if (message.type === 'utf8') { + console.log("Received: '" + message.utf8Data + "'"); + } + }); + + function sendNumber() { + if (connection.connected) { + var number = Math.round(Math.random() * 0xFFFFFF); + connection.sendUTF(number.toString()); + setTimeout(sendNumber, 1000); + } + } + sendNumber(); +}); + +client.connect('ws://localhost:8080/', 'echo-protocol'); +``` + +Client Example using the *W3C WebSocket API* +-------------------------------------------- + +Same example as above but using the [W3C WebSocket API](http://www.w3.org/TR/websockets/). + +```javascript +var W3CWebSocket = require('websocket').w3cwebsocket; + +var client = new W3CWebSocket('ws://localhost:8080/', 'echo-protocol'); + +client.onerror = function() { + console.log('Connection Error'); +}; + +client.onopen = function() { + console.log('WebSocket Client Connected'); + + function sendNumber() { + if (client.readyState === client.OPEN) { + var number = Math.round(Math.random() * 0xFFFFFF); + client.send(number.toString()); + setTimeout(sendNumber, 1000); + } + } + sendNumber(); +}; + +client.onclose = function() { + console.log('echo-protocol Client Closed'); +}; + +client.onmessage = function(e) { + if (typeof e.data === 'string') { + console.log("Received: '" + e.data + "'"); + } +}; +``` + +Request Router Example +---------------------- + +For an example of using the request router, see `libwebsockets-test-server.js` in the `test` folder. + + +Resources +--------- + +A presentation on the state of the WebSockets protocol that I gave on July 23, 2011 at the LA Hacker News meetup. [WebSockets: The Real-Time Web, Delivered](http://www.scribd.com/doc/60898569/WebSockets-The-Real-Time-Web-Delivered) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/binding.gyp b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/binding.gyp new file mode 100644 index 0000000000000000000000000000000000000000..77b2ed52ed5bd4ff255a7be51a6496b76d59f0f4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/binding.gyp @@ -0,0 +1,18 @@ +{ + 'targets': [ + { + 'target_name': 'validation', + 'include_dirs': ["<!(node -e \"require('nan')\")"], + 'cflags!': [ '-O3' ], + 'cflags': [ '-O2' ], + 'sources': [ 'src/validation.cc' ] + }, + { + 'target_name': 'bufferutil', + 'include_dirs': ["<!(node -e \"require('nan')\")"], + 'cflags!': [ '-O3' ], + 'cflags': [ '-O2' ], + 'sources': [ 'src/bufferutil.cc' ] + } + ] +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/Makefile b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/Makefile new file mode 100644 index 0000000000000000000000000000000000000000..72814773243119c9db5f3439e5b5cf285a20eb7c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/Makefile @@ -0,0 +1,320 @@ +# We borrow heavily from the kernel build setup, though we are simpler since +# we don't have Kconfig tweaking settings on us. + +# The implicit make rules have it looking for RCS files, among other things. +# We instead explicitly write all the rules we care about. +# It's even quicker (saves ~200ms) to pass -r on the command line. +MAKEFLAGS=-r + +# The source directory tree. +srcdir := .. +abs_srcdir := $(abspath $(srcdir)) + +# The name of the builddir. +builddir_name ?= . + +# The V=1 flag on command line makes us verbosely print command lines. +ifdef V + quiet= +else + quiet=quiet_ +endif + +# Specify BUILDTYPE=Release on the command line for a release build. +BUILDTYPE ?= Release + +# Directory all our build output goes into. +# Note that this must be two directories beneath src/ for unit tests to pass, +# as they reach into the src/ directory for data with relative paths. +builddir ?= $(builddir_name)/$(BUILDTYPE) +abs_builddir := $(abspath $(builddir)) +depsdir := $(builddir)/.deps + +# Object output directory. +obj := $(builddir)/obj +abs_obj := $(abspath $(obj)) + +# We build up a list of every single one of the targets so we can slurp in the +# generated dependency rule Makefiles in one pass. +all_deps := + + + +CC.target ?= $(CC) +CFLAGS.target ?= $(CPPFLAGS) $(CFLAGS) +CXX.target ?= $(CXX) +CXXFLAGS.target ?= $(CPPFLAGS) $(CXXFLAGS) +LINK.target ?= $(LINK) +LDFLAGS.target ?= $(LDFLAGS) +AR.target ?= $(AR) + +# C++ apps need to be linked with g++. +LINK ?= $(CXX.target) + +# TODO(evan): move all cross-compilation logic to gyp-time so we don't need +# to replicate this environment fallback in make as well. +CC.host ?= gcc +CFLAGS.host ?= $(CPPFLAGS_host) $(CFLAGS_host) +CXX.host ?= g++ +CXXFLAGS.host ?= $(CPPFLAGS_host) $(CXXFLAGS_host) +LINK.host ?= $(CXX.host) +LDFLAGS.host ?= +AR.host ?= ar + +# Define a dir function that can handle spaces. +# http://www.gnu.org/software/make/manual/make.html#Syntax-of-Functions +# "leading spaces cannot appear in the text of the first argument as written. +# These characters can be put into the argument value by variable substitution." +empty := +space := $(empty) $(empty) + +# http://stackoverflow.com/questions/1189781/using-make-dir-or-notdir-on-a-path-with-spaces +replace_spaces = $(subst $(space),?,$1) +unreplace_spaces = $(subst ?,$(space),$1) +dirx = $(call unreplace_spaces,$(dir $(call replace_spaces,$1))) + +# Flags to make gcc output dependency info. Note that you need to be +# careful here to use the flags that ccache and distcc can understand. +# We write to a dep file on the side first and then rename at the end +# so we can't end up with a broken dep file. +depfile = $(depsdir)/$(call replace_spaces,$@).d +DEPFLAGS = -MMD -MF $(depfile).raw + +# We have to fixup the deps output in a few ways. +# (1) the file output should mention the proper .o file. +# ccache or distcc lose the path to the target, so we convert a rule of +# the form: +# foobar.o: DEP1 DEP2 +# into +# path/to/foobar.o: DEP1 DEP2 +# (2) we want missing files not to cause us to fail to build. +# We want to rewrite +# foobar.o: DEP1 DEP2 \ +# DEP3 +# to +# DEP1: +# DEP2: +# DEP3: +# so if the files are missing, they're just considered phony rules. +# We have to do some pretty insane escaping to get those backslashes +# and dollar signs past make, the shell, and sed at the same time. +# Doesn't work with spaces, but that's fine: .d files have spaces in +# their names replaced with other characters. +define fixup_dep +# The depfile may not exist if the input file didn't have any #includes. +touch $(depfile).raw +# Fixup path as in (1). +sed -e "s|^$(notdir $@)|$@|" $(depfile).raw >> $(depfile) +# Add extra rules as in (2). +# We remove slashes and replace spaces with new lines; +# remove blank lines; +# delete the first line and append a colon to the remaining lines. +sed -e 's|\\||' -e 'y| |\n|' $(depfile).raw |\ + grep -v '^$$' |\ + sed -e 1d -e 's|$$|:|' \ + >> $(depfile) +rm $(depfile).raw +endef + +# Command definitions: +# - cmd_foo is the actual command to run; +# - quiet_cmd_foo is the brief-output summary of the command. + +quiet_cmd_cc = CC($(TOOLSET)) $@ +cmd_cc = $(CC.$(TOOLSET)) $(GYP_CFLAGS) $(DEPFLAGS) $(CFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_cxx = CXX($(TOOLSET)) $@ +cmd_cxx = $(CXX.$(TOOLSET)) $(GYP_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< + +quiet_cmd_objc = CXX($(TOOLSET)) $@ +cmd_objc = $(CC.$(TOOLSET)) $(GYP_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< + +quiet_cmd_objcxx = CXX($(TOOLSET)) $@ +cmd_objcxx = $(CXX.$(TOOLSET)) $(GYP_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# Commands for precompiled header files. +quiet_cmd_pch_c = CXX($(TOOLSET)) $@ +cmd_pch_c = $(CC.$(TOOLSET)) $(GYP_PCH_CFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_cc = CXX($(TOOLSET)) $@ +cmd_pch_cc = $(CC.$(TOOLSET)) $(GYP_PCH_CXXFLAGS) $(DEPFLAGS) $(CXXFLAGS.$(TOOLSET)) -c -o $@ $< +quiet_cmd_pch_m = CXX($(TOOLSET)) $@ +cmd_pch_m = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCFLAGS) $(DEPFLAGS) -c -o $@ $< +quiet_cmd_pch_mm = CXX($(TOOLSET)) $@ +cmd_pch_mm = $(CC.$(TOOLSET)) $(GYP_PCH_OBJCXXFLAGS) $(DEPFLAGS) -c -o $@ $< + +# gyp-mac-tool is written next to the root Makefile by gyp. +# Use $(4) for the command, since $(2) and $(3) are used as flag by do_cmd +# already. +quiet_cmd_mac_tool = MACTOOL $(4) $< +cmd_mac_tool = ./gyp-mac-tool $(4) $< "$@" + +quiet_cmd_mac_package_framework = PACKAGE FRAMEWORK $@ +cmd_mac_package_framework = ./gyp-mac-tool package-framework "$@" $(4) + +quiet_cmd_infoplist = INFOPLIST $@ +cmd_infoplist = $(CC.$(TOOLSET)) -E -P -Wno-trigraphs -x c $(INFOPLIST_DEFINES) "$<" -o "$@" + +quiet_cmd_touch = TOUCH $@ +cmd_touch = touch $@ + +quiet_cmd_copy = COPY $@ +# send stderr to /dev/null to ignore messages when linking directories. +cmd_copy = rm -rf "$@" && cp -af "$<" "$@" + +quiet_cmd_alink = LIBTOOL-STATIC $@ +cmd_alink = rm -f $@ && ./gyp-mac-tool filter-libtool libtool $(GYP_LIBTOOLFLAGS) -static -o $@ $(filter %.o,$^) + +quiet_cmd_link = LINK($(TOOLSET)) $@ +cmd_link = $(LINK.$(TOOLSET)) $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink = SOLINK($(TOOLSET)) $@ +cmd_solink = $(LINK.$(TOOLSET)) -shared $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o "$@" $(LD_INPUTS) $(LIBS) + +quiet_cmd_solink_module = SOLINK_MODULE($(TOOLSET)) $@ +cmd_solink_module = $(LINK.$(TOOLSET)) -bundle $(GYP_LDFLAGS) $(LDFLAGS.$(TOOLSET)) -o $@ $(filter-out FORCE_DO_CMD, $^) $(LIBS) + + +# Define an escape_quotes function to escape single quotes. +# This allows us to handle quotes properly as long as we always use +# use single quotes and escape_quotes. +escape_quotes = $(subst ','\'',$(1)) +# This comment is here just to include a ' to unconfuse syntax highlighting. +# Define an escape_vars function to escape '$' variable syntax. +# This allows us to read/write command lines with shell variables (e.g. +# $LD_LIBRARY_PATH), without triggering make substitution. +escape_vars = $(subst $$,$$$$,$(1)) +# Helper that expands to a shell command to echo a string exactly as it is in +# make. This uses printf instead of echo because printf's behaviour with respect +# to escape sequences is more portable than echo's across different shells +# (e.g., dash, bash). +exact_echo = printf '%s\n' '$(call escape_quotes,$(1))' + +# Helper to compare the command we're about to run against the command +# we logged the last time we ran the command. Produces an empty +# string (false) when the commands match. +# Tricky point: Make has no string-equality test function. +# The kernel uses the following, but it seems like it would have false +# positives, where one string reordered its arguments. +# arg_check = $(strip $(filter-out $(cmd_$(1)), $(cmd_$@)) \ +# $(filter-out $(cmd_$@), $(cmd_$(1)))) +# We instead substitute each for the empty string into the other, and +# say they're equal if both substitutions produce the empty string. +# .d files contain ? instead of spaces, take that into account. +command_changed = $(or $(subst $(cmd_$(1)),,$(cmd_$(call replace_spaces,$@))),\ + $(subst $(cmd_$(call replace_spaces,$@)),,$(cmd_$(1)))) + +# Helper that is non-empty when a prerequisite changes. +# Normally make does this implicitly, but we force rules to always run +# so we can check their command lines. +# $? -- new prerequisites +# $| -- order-only dependencies +prereq_changed = $(filter-out FORCE_DO_CMD,$(filter-out $|,$?)) + +# Helper that executes all postbuilds until one fails. +define do_postbuilds + @E=0;\ + for p in $(POSTBUILDS); do\ + eval $$p;\ + E=$$?;\ + if [ $$E -ne 0 ]; then\ + break;\ + fi;\ + done;\ + if [ $$E -ne 0 ]; then\ + rm -rf "$@";\ + exit $$E;\ + fi +endef + +# do_cmd: run a command via the above cmd_foo names, if necessary. +# Should always run for a given target to handle command-line changes. +# Second argument, if non-zero, makes it do asm/C/C++ dependency munging. +# Third argument, if non-zero, makes it do POSTBUILDS processing. +# Note: We intentionally do NOT call dirx for depfile, since it contains ? for +# spaces already and dirx strips the ? characters. +define do_cmd +$(if $(or $(command_changed),$(prereq_changed)), + @$(call exact_echo, $($(quiet)cmd_$(1))) + @mkdir -p "$(call dirx,$@)" "$(dir $(depfile))" + $(if $(findstring flock,$(word 2,$(cmd_$1))), + @$(cmd_$(1)) + @echo " $(quiet_cmd_$(1)): Finished", + @$(cmd_$(1)) + ) + @$(call exact_echo,$(call escape_vars,cmd_$(call replace_spaces,$@) := $(cmd_$(1)))) > $(depfile) + @$(if $(2),$(fixup_dep)) + $(if $(and $(3), $(POSTBUILDS)), + $(call do_postbuilds) + ) +) +endef + +# Declare the "all" target first so it is the default, +# even though we don't have the deps yet. +.PHONY: all +all: + +# make looks for ways to re-generate included makefiles, but in our case, we +# don't have a direct way. Explicitly telling make that it has nothing to do +# for them makes it go faster. +%.d: ; + +# Use FORCE_DO_CMD to force a target to run. Should be coupled with +# do_cmd. +.PHONY: FORCE_DO_CMD +FORCE_DO_CMD: + +TOOLSET := target +# Suffix rules, putting all outputs into $(obj). +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(srcdir)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +# Try building from generated source, too. +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj).$(TOOLSET)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + +$(obj).$(TOOLSET)/%.o: $(obj)/%.c FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cc FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cpp FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.cxx FORCE_DO_CMD + @$(call do_cmd,cxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.m FORCE_DO_CMD + @$(call do_cmd,objc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.mm FORCE_DO_CMD + @$(call do_cmd,objcxx,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.S FORCE_DO_CMD + @$(call do_cmd,cc,1) +$(obj).$(TOOLSET)/%.o: $(obj)/%.s FORCE_DO_CMD + @$(call do_cmd,cc,1) + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/bufferutil.target.mk b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/bufferutil.target.mk new file mode 100644 index 0000000000000000000000000000000000000000..c514c08ff522986fcd593a1d17ddf7f0f5731d3e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/bufferutil.target.mk @@ -0,0 +1,17 @@ +# This file is generated by gyp; do not edit. + +TOOLSET := target +TARGET := bufferutil +DEFS_Debug := \ + '-DNODE_GYP_MODULE_NAME=bufferutil' \ + '-DUSING_UV_SHARED=1' \ + '-DUSING_V8_SHARED=1' \ + '-DV8_DEPRECATION_WARNINGS=1' \ + '-D_DARWIN_USE_64_BIT_INODE=1' \ + '-D_LARGEFILE_SOURCE' \ + '-D_FILE_OFFSET_BITS=64' \ + '-DBUILDING_NODE_EXTENSION' \ + '-DDEBUG' \ + '-D_DEBUG' \ + '-DV8_ENABLE_CHECKS' + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/config.gypi b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/config.gypi new file mode 100644 index 0000000000000000000000000000000000000000..2b03da969939a0fec55a116113b81a9fcd593268 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/config.gypi @@ -0,0 +1,184 @@ +# Do not edit. File was generated by node-gyp's "configure" step +{ + "target_defaults": { + "cflags": [], + "default_configuration": "Release", + "defines": [], + "include_dirs": [], + "libraries": [] + }, + "variables": { + "asan": 0, + "coverage": "false", + "debug_devtools": "node", + "debug_http2": "false", + "debug_nghttp2": "false", + "force_dynamic_crt": 0, + "host_arch": "x64", + "icu_data_file": "icudt60l.dat", + "icu_data_in": "../../deps/icu-small/source/data/in/icudt60l.dat", + "icu_endianness": "l", + "icu_gyp_path": "tools/icu/icu-generic.gyp", + "icu_locales": "en,root", + "icu_path": "deps/icu-small", + "icu_small": "true", + "icu_ver_major": "60", + "llvm_version": 0, + "node_byteorder": "little", + "node_enable_d8": "false", + "node_enable_v8_vtunejit": "false", + "node_install_npm": "true", + "node_module_version": 57, + "node_no_browser_globals": "false", + "node_prefix": "/usr/local", + "node_release_urlbase": "https://nodejs.org/download/release/", + "node_shared": "false", + "node_shared_cares": "false", + "node_shared_http_parser": "false", + "node_shared_libuv": "false", + "node_shared_nghttp2": "false", + "node_shared_openssl": "false", + "node_shared_zlib": "false", + "node_tag": "", + "node_use_bundled_v8": "true", + "node_use_dtrace": "true", + "node_use_etw": "false", + "node_use_lttng": "false", + "node_use_openssl": "true", + "node_use_perfctr": "false", + "node_use_v8_platform": "true", + "node_without_node_options": "false", + "openssl_fips": "", + "openssl_no_asm": 0, + "shlib_suffix": "57.dylib", + "target_arch": "x64", + "uv_parent_path": "/deps/uv/", + "uv_use_dtrace": "true", + "v8_enable_gdbjit": 0, + "v8_enable_i18n_support": 1, + "v8_enable_inspector": 1, + "v8_no_strict_aliasing": 1, + "v8_optimized_debug": 0, + "v8_promise_internal_field_count": 1, + "v8_random_seed": 0, + "v8_trace_maps": 0, + "v8_use_snapshot": "true", + "want_separate_host_toolset": 0, + "xcode_version": "7.0", + "nodedir": "/Users/Kens/.node-gyp/8.10.0", + "standalone_static_library": 1, + "dry_run": "", + "legacy_bundling": "", + "save_dev": "", + "browser": "", + "commit_hooks": "true", + "only": "", + "viewer": "man", + "also": "", + "rollback": "true", + "usage": "", + "globalignorefile": "/usr/local/etc/npmignore", + "init_author_url": "", + "maxsockets": "50", + "shell": "/bin/bash", + "metrics_registry": "https://registry.npmjs.org/", + "parseable": "", + "shrinkwrap": "true", + "init_license": "ISC", + "timing": "", + "if_present": "", + "cache_max": "Infinity", + "init_author_email": "", + "sign_git_tag": "", + "cert": "", + "git_tag_version": "true", + "local_address": "", + "long": "", + "fetch_retries": "2", + "registry": "https://registry.npmjs.org/", + "key": "", + "message": "%s", + "versions": "", + "globalconfig": "/usr/local/etc/npmrc", + "always_auth": "", + "logs_max": "10", + "prefer_online": "", + "cache_lock_retries": "10", + "global_style": "", + "heading": "npm", + "fetch_retry_mintimeout": "10000", + "offline": "", + "read_only": "", + "searchlimit": "20", + "access": "", + "json": "", + "allow_same_version": "", + "description": "true", + "engine_strict": "", + "https_proxy": "", + "init_module": "/Users/Kens/.npm-init.js", + "userconfig": "/Users/Kens/.npmrc", + "cidr": "", + "node_version": "8.10.0", + "user": "", + "auth_type": "legacy", + "editor": "vi", + "ignore_prepublish": "", + "save": "true", + "script_shell": "", + "tag": "latest", + "global": "", + "progress": "true", + "ham_it_up": "", + "optional": "true", + "searchstaleness": "900", + "bin_links": "true", + "force": "", + "save_prod": "", + "searchopts": "", + "depth": "Infinity", + "node_gyp": "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js", + "rebuild_bundle": "true", + "sso_poll_frequency": "500", + "unicode": "true", + "fetch_retry_maxtimeout": "60000", + "ca": "", + "save_prefix": "^", + "scripts_prepend_node_path": "warn-only", + "sso_type": "oauth", + "strict_ssl": "true", + "tag_version_prefix": "v", + "dev": "", + "fetch_retry_factor": "10", + "group": "20", + "save_exact": "", + "cache_lock_stale": "60000", + "prefer_offline": "", + "version": "", + "cache_min": "10", + "otp": "", + "cache": "/Users/Kens/.npm", + "searchexclude": "", + "color": "true", + "package_lock": "true", + "package_lock_only": "", + "save_optional": "", + "user_agent": "npm/5.6.0 node/v8.10.0 darwin x64", + "ignore_scripts": "", + "cache_lock_wait": "10000", + "production": "", + "save_bundle": "", + "send_metrics": "", + "init_version": "1.0.0", + "node_options": "", + "umask": "0022", + "scope": "", + "git": "git", + "init_author_name": "", + "onload_script": "", + "tmp": "/var/folders/4d/ktz4cr454210y7dr_89c40lh0000gp/T", + "unsafe_perm": "true", + "link": "", + "prefix": "/usr/local" + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/gyp-mac-tool b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/gyp-mac-tool new file mode 100644 index 0000000000000000000000000000000000000000..8ef02b0493a003a05a90aff8975351e5f18fa85b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/build/gyp-mac-tool @@ -0,0 +1,611 @@ +#!/usr/bin/env python +# Generated by gyp. Do not edit. +# Copyright (c) 2012 Google Inc. All rights reserved. +# Use of this source code is governed by a BSD-style license that can be +# found in the LICENSE file. + +"""Utility functions to perform Xcode-style build steps. + +These functions are executed via gyp-mac-tool when using the Makefile generator. +""" + +import fcntl +import fnmatch +import glob +import json +import os +import plistlib +import re +import shutil +import string +import subprocess +import sys +import tempfile + + +def main(args): + executor = MacTool() + exit_code = executor.Dispatch(args) + if exit_code is not None: + sys.exit(exit_code) + + +class MacTool(object): + """This class performs all the Mac tooling steps. The methods can either be + executed directly, or dispatched from an argument list.""" + + def Dispatch(self, args): + """Dispatches a string command to a method.""" + if len(args) < 1: + raise Exception("Not enough arguments") + + method = "Exec%s" % self._CommandifyName(args[0]) + return getattr(self, method)(*args[1:]) + + def _CommandifyName(self, name_string): + """Transforms a tool name like copy-info-plist to CopyInfoPlist""" + return name_string.title().replace('-', '') + + def ExecCopyBundleResource(self, source, dest, convert_to_binary): + """Copies a resource file to the bundle/Resources directory, performing any + necessary compilation on each resource.""" + extension = os.path.splitext(source)[1].lower() + if os.path.isdir(source): + # Copy tree. + # TODO(thakis): This copies file attributes like mtime, while the + # single-file branch below doesn't. This should probably be changed to + # be consistent with the single-file branch. + if os.path.exists(dest): + shutil.rmtree(dest) + shutil.copytree(source, dest) + elif extension == '.xib': + return self._CopyXIBFile(source, dest) + elif extension == '.storyboard': + return self._CopyXIBFile(source, dest) + elif extension == '.strings': + self._CopyStringsFile(source, dest, convert_to_binary) + else: + shutil.copy(source, dest) + + def _CopyXIBFile(self, source, dest): + """Compiles a XIB file with ibtool into a binary plist in the bundle.""" + + # ibtool sometimes crashes with relative paths. See crbug.com/314728. + base = os.path.dirname(os.path.realpath(__file__)) + if os.path.relpath(source): + source = os.path.join(base, source) + if os.path.relpath(dest): + dest = os.path.join(base, dest) + + args = ['xcrun', 'ibtool', '--errors', '--warnings', '--notices', + '--output-format', 'human-readable-text', '--compile', dest, source] + ibtool_section_re = re.compile(r'/\*.*\*/') + ibtool_re = re.compile(r'.*note:.*is clipping its content') + ibtoolout = subprocess.Popen(args, stdout=subprocess.PIPE) + current_section_header = None + for line in ibtoolout.stdout: + if ibtool_section_re.match(line): + current_section_header = line + elif not ibtool_re.match(line): + if current_section_header: + sys.stdout.write(current_section_header) + current_section_header = None + sys.stdout.write(line) + return ibtoolout.returncode + + def _ConvertToBinary(self, dest): + subprocess.check_call([ + 'xcrun', 'plutil', '-convert', 'binary1', '-o', dest, dest]) + + def _CopyStringsFile(self, source, dest, convert_to_binary): + """Copies a .strings file using iconv to reconvert the input into UTF-16.""" + input_code = self._DetectInputEncoding(source) or "UTF-8" + + # Xcode's CpyCopyStringsFile / builtin-copyStrings seems to call + # CFPropertyListCreateFromXMLData() behind the scenes; at least it prints + # CFPropertyListCreateFromXMLData(): Old-style plist parser: missing + # semicolon in dictionary. + # on invalid files. Do the same kind of validation. + import CoreFoundation + s = open(source, 'rb').read() + d = CoreFoundation.CFDataCreate(None, s, len(s)) + _, error = CoreFoundation.CFPropertyListCreateFromXMLData(None, d, 0, None) + if error: + return + + fp = open(dest, 'wb') + fp.write(s.decode(input_code).encode('UTF-16')) + fp.close() + + if convert_to_binary == 'True': + self._ConvertToBinary(dest) + + def _DetectInputEncoding(self, file_name): + """Reads the first few bytes from file_name and tries to guess the text + encoding. Returns None as a guess if it can't detect it.""" + fp = open(file_name, 'rb') + try: + header = fp.read(3) + except e: + fp.close() + return None + fp.close() + if header.startswith("\xFE\xFF"): + return "UTF-16" + elif header.startswith("\xFF\xFE"): + return "UTF-16" + elif header.startswith("\xEF\xBB\xBF"): + return "UTF-8" + else: + return None + + def ExecCopyInfoPlist(self, source, dest, convert_to_binary, *keys): + """Copies the |source| Info.plist to the destination directory |dest|.""" + # Read the source Info.plist into memory. + fd = open(source, 'r') + lines = fd.read() + fd.close() + + # Insert synthesized key/value pairs (e.g. BuildMachineOSBuild). + plist = plistlib.readPlistFromString(lines) + if keys: + plist = dict(plist.items() + json.loads(keys[0]).items()) + lines = plistlib.writePlistToString(plist) + + # Go through all the environment variables and replace them as variables in + # the file. + IDENT_RE = re.compile(r'[/\s]') + for key in os.environ: + if key.startswith('_'): + continue + evar = '${%s}' % key + evalue = os.environ[key] + lines = string.replace(lines, evar, evalue) + + # Xcode supports various suffices on environment variables, which are + # all undocumented. :rfc1034identifier is used in the standard project + # template these days, and :identifier was used earlier. They are used to + # convert non-url characters into things that look like valid urls -- + # except that the replacement character for :identifier, '_' isn't valid + # in a URL either -- oops, hence :rfc1034identifier was born. + evar = '${%s:identifier}' % key + evalue = IDENT_RE.sub('_', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + evar = '${%s:rfc1034identifier}' % key + evalue = IDENT_RE.sub('-', os.environ[key]) + lines = string.replace(lines, evar, evalue) + + # Remove any keys with values that haven't been replaced. + lines = lines.split('\n') + for i in range(len(lines)): + if lines[i].strip().startswith("<string>${"): + lines[i] = None + lines[i - 1] = None + lines = '\n'.join(filter(lambda x: x is not None, lines)) + + # Write out the file with variables replaced. + fd = open(dest, 'w') + fd.write(lines) + fd.close() + + # Now write out PkgInfo file now that the Info.plist file has been + # "compiled". + self._WritePkgInfo(dest) + + if convert_to_binary == 'True': + self._ConvertToBinary(dest) + + def _WritePkgInfo(self, info_plist): + """This writes the PkgInfo file from the data stored in Info.plist.""" + plist = plistlib.readPlist(info_plist) + if not plist: + return + + # Only create PkgInfo for executable types. + package_type = plist['CFBundlePackageType'] + if package_type != 'APPL': + return + + # The format of PkgInfo is eight characters, representing the bundle type + # and bundle signature, each four characters. If that is missing, four + # '?' characters are used instead. + signature_code = plist.get('CFBundleSignature', '????') + if len(signature_code) != 4: # Wrong length resets everything, too. + signature_code = '?' * 4 + + dest = os.path.join(os.path.dirname(info_plist), 'PkgInfo') + fp = open(dest, 'w') + fp.write('%s%s' % (package_type, signature_code)) + fp.close() + + def ExecFlock(self, lockfile, *cmd_list): + """Emulates the most basic behavior of Linux's flock(1).""" + # Rely on exception handling to report errors. + fd = os.open(lockfile, os.O_RDONLY|os.O_NOCTTY|os.O_CREAT, 0o666) + fcntl.flock(fd, fcntl.LOCK_EX) + return subprocess.call(cmd_list) + + def ExecFilterLibtool(self, *cmd_list): + """Calls libtool and filters out '/path/to/libtool: file: foo.o has no + symbols'.""" + libtool_re = re.compile(r'^.*libtool: file: .* has no symbols$') + libtool_re5 = re.compile( + r'^.*libtool: warning for library: ' + + r'.* the table of contents is empty ' + + r'\(no object file members in the library define global symbols\)$') + env = os.environ.copy() + # Ref: + # http://www.opensource.apple.com/source/cctools/cctools-809/misc/libtool.c + # The problem with this flag is that it resets the file mtime on the file to + # epoch=0, e.g. 1970-1-1 or 1969-12-31 depending on timezone. + env['ZERO_AR_DATE'] = '1' + libtoolout = subprocess.Popen(cmd_list, stderr=subprocess.PIPE, env=env) + _, err = libtoolout.communicate() + for line in err.splitlines(): + if not libtool_re.match(line) and not libtool_re5.match(line): + print >>sys.stderr, line + # Unconditionally touch the output .a file on the command line if present + # and the command succeeded. A bit hacky. + if not libtoolout.returncode: + for i in range(len(cmd_list) - 1): + if cmd_list[i] == "-o" and cmd_list[i+1].endswith('.a'): + os.utime(cmd_list[i+1], None) + break + return libtoolout.returncode + + def ExecPackageFramework(self, framework, version): + """Takes a path to Something.framework and the Current version of that and + sets up all the symlinks.""" + # Find the name of the binary based on the part before the ".framework". + binary = os.path.basename(framework).split('.')[0] + + CURRENT = 'Current' + RESOURCES = 'Resources' + VERSIONS = 'Versions' + + if not os.path.exists(os.path.join(framework, VERSIONS, version, binary)): + # Binary-less frameworks don't seem to contain symlinks (see e.g. + # chromium's out/Debug/org.chromium.Chromium.manifest/ bundle). + return + + # Move into the framework directory to set the symlinks correctly. + pwd = os.getcwd() + os.chdir(framework) + + # Set up the Current version. + self._Relink(version, os.path.join(VERSIONS, CURRENT)) + + # Set up the root symlinks. + self._Relink(os.path.join(VERSIONS, CURRENT, binary), binary) + self._Relink(os.path.join(VERSIONS, CURRENT, RESOURCES), RESOURCES) + + # Back to where we were before! + os.chdir(pwd) + + def _Relink(self, dest, link): + """Creates a symlink to |dest| named |link|. If |link| already exists, + it is overwritten.""" + if os.path.lexists(link): + os.remove(link) + os.symlink(dest, link) + + def ExecCompileXcassets(self, keys, *inputs): + """Compiles multiple .xcassets files into a single .car file. + + This invokes 'actool' to compile all the inputs .xcassets files. The + |keys| arguments is a json-encoded dictionary of extra arguments to + pass to 'actool' when the asset catalogs contains an application icon + or a launch image. + + Note that 'actool' does not create the Assets.car file if the asset + catalogs does not contains imageset. + """ + command_line = [ + 'xcrun', 'actool', '--output-format', 'human-readable-text', + '--compress-pngs', '--notices', '--warnings', '--errors', + ] + is_iphone_target = 'IPHONEOS_DEPLOYMENT_TARGET' in os.environ + if is_iphone_target: + platform = os.environ['CONFIGURATION'].split('-')[-1] + if platform not in ('iphoneos', 'iphonesimulator'): + platform = 'iphonesimulator' + command_line.extend([ + '--platform', platform, '--target-device', 'iphone', + '--target-device', 'ipad', '--minimum-deployment-target', + os.environ['IPHONEOS_DEPLOYMENT_TARGET'], '--compile', + os.path.abspath(os.environ['CONTENTS_FOLDER_PATH']), + ]) + else: + command_line.extend([ + '--platform', 'macosx', '--target-device', 'mac', + '--minimum-deployment-target', os.environ['MACOSX_DEPLOYMENT_TARGET'], + '--compile', + os.path.abspath(os.environ['UNLOCALIZED_RESOURCES_FOLDER_PATH']), + ]) + if keys: + keys = json.loads(keys) + for key, value in keys.iteritems(): + arg_name = '--' + key + if isinstance(value, bool): + if value: + command_line.append(arg_name) + elif isinstance(value, list): + for v in value: + command_line.append(arg_name) + command_line.append(str(v)) + else: + command_line.append(arg_name) + command_line.append(str(value)) + # Note: actool crashes if inputs path are relative, so use os.path.abspath + # to get absolute path name for inputs. + command_line.extend(map(os.path.abspath, inputs)) + subprocess.check_call(command_line) + + def ExecMergeInfoPlist(self, output, *inputs): + """Merge multiple .plist files into a single .plist file.""" + merged_plist = {} + for path in inputs: + plist = self._LoadPlistMaybeBinary(path) + self._MergePlist(merged_plist, plist) + plistlib.writePlist(merged_plist, output) + + def ExecCodeSignBundle(self, key, resource_rules, entitlements, provisioning): + """Code sign a bundle. + + This function tries to code sign an iOS bundle, following the same + algorithm as Xcode: + 1. copy ResourceRules.plist from the user or the SDK into the bundle, + 2. pick the provisioning profile that best match the bundle identifier, + and copy it into the bundle as embedded.mobileprovision, + 3. copy Entitlements.plist from user or SDK next to the bundle, + 4. code sign the bundle. + """ + resource_rules_path = self._InstallResourceRules(resource_rules) + substitutions, overrides = self._InstallProvisioningProfile( + provisioning, self._GetCFBundleIdentifier()) + entitlements_path = self._InstallEntitlements( + entitlements, substitutions, overrides) + subprocess.check_call([ + 'codesign', '--force', '--sign', key, '--resource-rules', + resource_rules_path, '--entitlements', entitlements_path, + os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['FULL_PRODUCT_NAME'])]) + + def _InstallResourceRules(self, resource_rules): + """Installs ResourceRules.plist from user or SDK into the bundle. + + Args: + resource_rules: string, optional, path to the ResourceRules.plist file + to use, default to "${SDKROOT}/ResourceRules.plist" + + Returns: + Path to the copy of ResourceRules.plist into the bundle. + """ + source_path = resource_rules + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'ResourceRules.plist') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], 'ResourceRules.plist') + shutil.copy2(source_path, target_path) + return target_path + + def _InstallProvisioningProfile(self, profile, bundle_identifier): + """Installs embedded.mobileprovision into the bundle. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple containing two dictionary: variables substitutions and values + to overrides when generating the entitlements file. + """ + source_path, provisioning_data, team_id = self._FindProvisioningProfile( + profile, bundle_identifier) + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['CONTENTS_FOLDER_PATH'], + 'embedded.mobileprovision') + shutil.copy2(source_path, target_path) + substitutions = self._GetSubstitutions(bundle_identifier, team_id + '.') + return substitutions, provisioning_data['Entitlements'] + + def _FindProvisioningProfile(self, profile, bundle_identifier): + """Finds the .mobileprovision file to use for signing the bundle. + + Checks all the installed provisioning profiles (or if the user specified + the PROVISIONING_PROFILE variable, only consult it) and select the most + specific that correspond to the bundle identifier. + + Args: + profile: string, optional, short name of the .mobileprovision file + to use, if empty or the file is missing, the best file installed + will be used + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + + Returns: + A tuple of the path to the selected provisioning profile, the data of + the embedded plist in the provisioning profile and the team identifier + to use for code signing. + + Raises: + SystemExit: if no .mobileprovision can be used to sign the bundle. + """ + profiles_dir = os.path.join( + os.environ['HOME'], 'Library', 'MobileDevice', 'Provisioning Profiles') + if not os.path.isdir(profiles_dir): + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + provisioning_profiles = None + if profile: + profile_path = os.path.join(profiles_dir, profile + '.mobileprovision') + if os.path.exists(profile_path): + provisioning_profiles = [profile_path] + if not provisioning_profiles: + provisioning_profiles = glob.glob( + os.path.join(profiles_dir, '*.mobileprovision')) + valid_provisioning_profiles = {} + for profile_path in provisioning_profiles: + profile_data = self._LoadProvisioningProfile(profile_path) + app_id_pattern = profile_data.get( + 'Entitlements', {}).get('application-identifier', '') + for team_identifier in profile_data.get('TeamIdentifier', []): + app_id = '%s.%s' % (team_identifier, bundle_identifier) + if fnmatch.fnmatch(app_id, app_id_pattern): + valid_provisioning_profiles[app_id_pattern] = ( + profile_path, profile_data, team_identifier) + if not valid_provisioning_profiles: + print >>sys.stderr, ( + 'cannot find mobile provisioning for %s' % bundle_identifier) + sys.exit(1) + # If the user has multiple provisioning profiles installed that can be + # used for ${bundle_identifier}, pick the most specific one (ie. the + # provisioning profile whose pattern is the longest). + selected_key = max(valid_provisioning_profiles, key=lambda v: len(v)) + return valid_provisioning_profiles[selected_key] + + def _LoadProvisioningProfile(self, profile_path): + """Extracts the plist embedded in a provisioning profile. + + Args: + profile_path: string, path to the .mobileprovision file + + Returns: + Content of the plist embedded in the provisioning profile as a dictionary. + """ + with tempfile.NamedTemporaryFile() as temp: + subprocess.check_call([ + 'security', 'cms', '-D', '-i', profile_path, '-o', temp.name]) + return self._LoadPlistMaybeBinary(temp.name) + + def _MergePlist(self, merged_plist, plist): + """Merge |plist| into |merged_plist|.""" + for key, value in plist.iteritems(): + if isinstance(value, dict): + merged_value = merged_plist.get(key, {}) + if isinstance(merged_value, dict): + self._MergePlist(merged_value, value) + merged_plist[key] = merged_value + else: + merged_plist[key] = value + else: + merged_plist[key] = value + + def _LoadPlistMaybeBinary(self, plist_path): + """Loads into a memory a plist possibly encoded in binary format. + + This is a wrapper around plistlib.readPlist that tries to convert the + plist to the XML format if it can't be parsed (assuming that it is in + the binary format). + + Args: + plist_path: string, path to a plist file, in XML or binary format + + Returns: + Content of the plist as a dictionary. + """ + try: + # First, try to read the file using plistlib that only supports XML, + # and if an exception is raised, convert a temporary copy to XML and + # load that copy. + return plistlib.readPlist(plist_path) + except: + pass + with tempfile.NamedTemporaryFile() as temp: + shutil.copy2(plist_path, temp.name) + subprocess.check_call(['plutil', '-convert', 'xml1', temp.name]) + return plistlib.readPlist(temp.name) + + def _GetSubstitutions(self, bundle_identifier, app_identifier_prefix): + """Constructs a dictionary of variable substitutions for Entitlements.plist. + + Args: + bundle_identifier: string, value of CFBundleIdentifier from Info.plist + app_identifier_prefix: string, value for AppIdentifierPrefix + + Returns: + Dictionary of substitutions to apply when generating Entitlements.plist. + """ + return { + 'CFBundleIdentifier': bundle_identifier, + 'AppIdentifierPrefix': app_identifier_prefix, + } + + def _GetCFBundleIdentifier(self): + """Extracts CFBundleIdentifier value from Info.plist in the bundle. + + Returns: + Value of CFBundleIdentifier in the Info.plist located in the bundle. + """ + info_plist_path = os.path.join( + os.environ['TARGET_BUILD_DIR'], + os.environ['INFOPLIST_PATH']) + info_plist_data = self._LoadPlistMaybeBinary(info_plist_path) + return info_plist_data['CFBundleIdentifier'] + + def _InstallEntitlements(self, entitlements, substitutions, overrides): + """Generates and install the ${BundleName}.xcent entitlements file. + + Expands variables "$(variable)" pattern in the source entitlements file, + add extra entitlements defined in the .mobileprovision file and the copy + the generated plist to "${BundlePath}.xcent". + + Args: + entitlements: string, optional, path to the Entitlements.plist template + to use, defaults to "${SDKROOT}/Entitlements.plist" + substitutions: dictionary, variable substitutions + overrides: dictionary, values to add to the entitlements + + Returns: + Path to the generated entitlements file. + """ + source_path = entitlements + target_path = os.path.join( + os.environ['BUILT_PRODUCTS_DIR'], + os.environ['PRODUCT_NAME'] + '.xcent') + if not source_path: + source_path = os.path.join( + os.environ['SDKROOT'], + 'Entitlements.plist') + shutil.copy2(source_path, target_path) + data = self._LoadPlistMaybeBinary(target_path) + data = self._ExpandVariables(data, substitutions) + if overrides: + for key in overrides: + if key not in data: + data[key] = overrides[key] + plistlib.writePlist(data, target_path) + return target_path + + def _ExpandVariables(self, data, substitutions): + """Expands variables "$(variable)" in data. + + Args: + data: object, can be either string, list or dictionary + substitutions: dictionary, variable substitutions to perform + + Returns: + Copy of data where each references to "$(variable)" has been replaced + by the corresponding value found in substitutions, or left intact if + the key was not found. + """ + if isinstance(data, str): + for key, value in substitutions.iteritems(): + data = data.replace('$(%s)' % key, value) + return data + if isinstance(data, list): + return [self._ExpandVariables(v, substitutions) for v in data] + if isinstance(data, dict): + return {k: self._ExpandVariables(data[k], substitutions) for k in data} + return data + +if __name__ == '__main__': + sys.exit(main(sys.argv[1:])) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/builderror.log b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/builderror.log new file mode 100644 index 0000000000000000000000000000000000000000..088a9a348d3382e61bac89e5210f461e70420680 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/builderror.log @@ -0,0 +1,23 @@ +xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance + +xcode-select: error: tool 'xcodebuild' requires Xcode, but active developer directory '/Library/Developer/CommandLineTools' is a command line tools instance + +No receipt for 'com.apple.pkg.CLTools_Executables' found at '/'. + +No receipt for 'com.apple.pkg.DeveloperToolsCLILeo' found at '/'. + +No receipt for 'com.apple.pkg.DeveloperToolsCLI' found at '/'. + +gyp: No Xcode or CLT version detected! +gyp ERR! configure error +gyp ERR! stack Error: `gyp` failed with exit code: 1 +gyp ERR! stack at ChildProcess.onCpExit (/usr/local/lib/node_modules/npm/node_modules/node-gyp/lib/configure.js:336:16) +gyp ERR! stack at emitTwo (events.js:126:13) +gyp ERR! stack at ChildProcess.emit (events.js:214:7) +gyp ERR! stack at Process.ChildProcess._handle.onexit (internal/child_process.js:198:12) +gyp ERR! System Darwin 17.4.0 +gyp ERR! command "/usr/local/bin/node" "/usr/local/lib/node_modules/npm/node_modules/node-gyp/bin/node-gyp.js" "rebuild" +gyp ERR! cwd /Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket +gyp ERR! node -v v8.10.0 +gyp ERR! node-gyp -v v3.6.2 +gyp ERR! not ok diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/gulpfile.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..b515b928534ef9bdd757d0e9a445bf5f35f67c48 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/gulpfile.js @@ -0,0 +1,14 @@ +/** + * Dependencies. + */ +var gulp = require('gulp'); +var jshint = require('gulp-jshint'); + +gulp.task('lint', function() { + return gulp.src(['gulpfile.js', 'lib/**/*.js', 'test/**/*.js']) + .pipe(jshint('.jshintrc')) + .pipe(jshint.reporter('jshint-stylish', {verbose: true})) + .pipe(jshint.reporter('fail')); +}); + +gulp.task('default', gulp.series('lint')); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/index.js new file mode 100644 index 0000000000000000000000000000000000000000..573969f7ce3fdaef6914a0a5da33f5d400b9fd49 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/index.js @@ -0,0 +1 @@ +module.exports = require('./lib/websocket'); \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.fallback.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.fallback.js new file mode 100644 index 0000000000000000000000000000000000000000..de18bfb8102fe2e539b2b4ac60a0f5b70a6571b8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.fallback.js @@ -0,0 +1,52 @@ +/*! + * Copied from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +/* jshint -W086 */ + +module.exports.BufferUtil = { + merge: function(mergedBuffer, buffers) { + var offset = 0; + for (var i = 0, l = buffers.length; i < l; ++i) { + var buf = buffers[i]; + buf.copy(mergedBuffer, offset); + offset += buf.length; + } + }, + mask: function(source, mask, output, offset, length) { + var maskNum = mask.readUInt32LE(0, true); + var i = 0; + for (; i < length - 3; i += 4) { + var num = maskNum ^ source.readUInt32LE(i, true); + if (num < 0) { num = 4294967296 + num; } + output.writeUInt32LE(num, offset + i, true); + } + switch (length % 4) { + case 3: output[offset + i + 2] = source[i + 2] ^ mask[2]; + case 2: output[offset + i + 1] = source[i + 1] ^ mask[1]; + case 1: output[offset + i] = source[i] ^ mask[0]; + case 0: + } + }, + unmask: function(data, mask) { + var maskNum = mask.readUInt32LE(0, true); + var length = data.length; + var i = 0; + for (; i < length - 3; i += 4) { + var num = maskNum ^ data.readUInt32LE(i, true); + if (num < 0) { num = 4294967296 + num; } + data.writeUInt32LE(num, i, true); + } + switch (length % 4) { + case 3: data[i + 2] = data[i + 2] ^ mask[2]; + case 2: data[i + 1] = data[i + 1] ^ mask[1]; + case 1: data[i] = data[i] ^ mask[0]; + case 0: + } + } +}; + +/* jshint +W086 */ \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.js new file mode 100644 index 0000000000000000000000000000000000000000..fa37c8082c13465f1104f6edff2cf6bed5a9ec29 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/BufferUtil.js @@ -0,0 +1,17 @@ +/*! + * Copied from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +try { + module.exports = require('../build/Release/bufferutil'); +} catch (e) { try { + module.exports = require('../build/default/bufferutil'); +} catch (e) { try { + module.exports = require('./BufferUtil.fallback'); +} catch (e) { + console.error('bufferutil.node seems to not have been built. Run npm install.'); + throw e; +}}} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Deprecation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Deprecation.js new file mode 100644 index 0000000000000000000000000000000000000000..094f160481790fa017b89e4661b6ae9566239315 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Deprecation.js @@ -0,0 +1,32 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var Deprecation = { + disableWarnings: false, + + deprecationWarningMap: { + + }, + + warn: function(deprecationName) { + if (!this.disableWarnings && this.deprecationWarningMap[deprecationName]) { + console.warn('DEPRECATION WARNING: ' + this.deprecationWarningMap[deprecationName]); + this.deprecationWarningMap[deprecationName] = false; + } + } +}; + +module.exports = Deprecation; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.fallback.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.fallback.js new file mode 100644 index 0000000000000000000000000000000000000000..6160f888b7e3355a6298881c670f83069ea5b7e3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.fallback.js @@ -0,0 +1,12 @@ +/*! + * UTF-8 Validation Fallback Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +module.exports.Validation = { + isValidUTF8: function() { + return true; + } +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.js new file mode 100644 index 0000000000000000000000000000000000000000..b4106e8d8356edd980b2c43b71b5ee1b4d4f27d3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/Validation.js @@ -0,0 +1,17 @@ +/*! + * UTF-8 Validation Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2011 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +try { + module.exports = require('../build/Release/validation'); +} catch (e) { try { + module.exports = require('../build/default/validation'); +} catch (e) { try { + module.exports = require('./Validation.fallback'); +} catch (e) { + console.error('validation.node seems not to have been built. Run npm install.'); + throw e; +}}} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/W3CWebSocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/W3CWebSocket.js new file mode 100644 index 0000000000000000000000000000000000000000..44a4ac98ebf524f7b2a02fff77c0c92935299844 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/W3CWebSocket.js @@ -0,0 +1,257 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var WebSocketClient = require('./WebSocketClient'); +var toBuffer = require('typedarray-to-buffer'); +var yaeti = require('yaeti'); + + +const CONNECTING = 0; +const OPEN = 1; +const CLOSING = 2; +const CLOSED = 3; + + +module.exports = W3CWebSocket; + + +function W3CWebSocket(url, protocols, origin, headers, requestOptions, clientConfig) { + // Make this an EventTarget. + yaeti.EventTarget.call(this); + + // Sanitize clientConfig. + clientConfig = clientConfig || {}; + clientConfig.assembleFragments = true; // Required in the W3C API. + + var self = this; + + this._url = url; + this._readyState = CONNECTING; + this._protocol = undefined; + this._extensions = ''; + this._bufferedAmount = 0; // Hack, always 0. + this._binaryType = 'arraybuffer'; // TODO: Should be 'blob' by default, but Node has no Blob. + + // The WebSocketConnection instance. + this._connection = undefined; + + // WebSocketClient instance. + this._client = new WebSocketClient(clientConfig); + + this._client.on('connect', function(connection) { + onConnect.call(self, connection); + }); + + this._client.on('connectFailed', function() { + onConnectFailed.call(self); + }); + + this._client.connect(url, protocols, origin, headers, requestOptions); +} + + +// Expose W3C read only attributes. +Object.defineProperties(W3CWebSocket.prototype, { + url: { get: function() { return this._url; } }, + readyState: { get: function() { return this._readyState; } }, + protocol: { get: function() { return this._protocol; } }, + extensions: { get: function() { return this._extensions; } }, + bufferedAmount: { get: function() { return this._bufferedAmount; } } +}); + + +// Expose W3C write/read attributes. +Object.defineProperties(W3CWebSocket.prototype, { + binaryType: { + get: function() { + return this._binaryType; + }, + set: function(type) { + // TODO: Just 'arraybuffer' supported. + if (type !== 'arraybuffer') { + throw new SyntaxError('just "arraybuffer" type allowed for "binaryType" attribute'); + } + this._binaryType = type; + } + } +}); + + +// Expose W3C readyState constants into the WebSocket instance as W3C states. +[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) { + Object.defineProperty(W3CWebSocket.prototype, property[0], { + get: function() { return property[1]; } + }); +}); + +// Also expose W3C readyState constants into the WebSocket class (not defined by the W3C, +// but there are so many libs relying on them). +[['CONNECTING',CONNECTING], ['OPEN',OPEN], ['CLOSING',CLOSING], ['CLOSED',CLOSED]].forEach(function(property) { + Object.defineProperty(W3CWebSocket, property[0], { + get: function() { return property[1]; } + }); +}); + + +W3CWebSocket.prototype.send = function(data) { + if (this._readyState !== OPEN) { + throw new Error('cannot call send() while not connected'); + } + + // Text. + if (typeof data === 'string' || data instanceof String) { + this._connection.sendUTF(data); + } + // Binary. + else { + // Node Buffer. + if (data instanceof Buffer) { + this._connection.sendBytes(data); + } + // If ArrayBuffer or ArrayBufferView convert it to Node Buffer. + else if (data.byteLength || data.byteLength === 0) { + data = toBuffer(data); + this._connection.sendBytes(data); + } + else { + throw new Error('unknown binary data:', data); + } + } +}; + + +W3CWebSocket.prototype.close = function(code, reason) { + switch(this._readyState) { + case CONNECTING: + // NOTE: We don't have the WebSocketConnection instance yet so no + // way to close the TCP connection. + // Artificially invoke the onConnectFailed event. + onConnectFailed.call(this); + // And close if it connects after a while. + this._client.on('connect', function(connection) { + if (code) { + connection.close(code, reason); + } else { + connection.close(); + } + }); + break; + case OPEN: + this._readyState = CLOSING; + if (code) { + this._connection.close(code, reason); + } else { + this._connection.close(); + } + break; + case CLOSING: + case CLOSED: + break; + } +}; + + +/** + * Private API. + */ + + +function createCloseEvent(code, reason) { + var event = new yaeti.Event('close'); + + event.code = code; + event.reason = reason; + event.wasClean = (typeof code === 'undefined' || code === 1000); + + return event; +} + + +function createMessageEvent(data) { + var event = new yaeti.Event('message'); + + event.data = data; + + return event; +} + + +function onConnect(connection) { + var self = this; + + this._readyState = OPEN; + this._connection = connection; + this._protocol = connection.protocol; + this._extensions = connection.extensions; + + this._connection.on('close', function(code, reason) { + onClose.call(self, code, reason); + }); + + this._connection.on('message', function(msg) { + onMessage.call(self, msg); + }); + + this.dispatchEvent(new yaeti.Event('open')); +} + + +function onConnectFailed() { + destroy.call(this); + this._readyState = CLOSED; + + try { + this.dispatchEvent(new yaeti.Event('error')); + } finally { + this.dispatchEvent(createCloseEvent(1006, 'connection failed')); + } +} + + +function onClose(code, reason) { + destroy.call(this); + this._readyState = CLOSED; + + this.dispatchEvent(createCloseEvent(code, reason || '')); +} + + +function onMessage(message) { + if (message.utf8Data) { + this.dispatchEvent(createMessageEvent(message.utf8Data)); + } + else if (message.binaryData) { + // Must convert from Node Buffer to ArrayBuffer. + // TODO: or to a Blob (which does not exist in Node!). + if (this.binaryType === 'arraybuffer') { + var buffer = message.binaryData; + var arraybuffer = new ArrayBuffer(buffer.length); + var view = new Uint8Array(arraybuffer); + for (var i=0, len=buffer.length; i<len; ++i) { + view[i] = buffer[i]; + } + this.dispatchEvent(createMessageEvent(arraybuffer)); + } + } +} + + +function destroy() { + this._client.removeAllListeners(); + if (this._connection) { + this._connection.removeAllListeners(); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketClient.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketClient.js new file mode 100644 index 0000000000000000000000000000000000000000..3b24beb8bde7ee86956e5cf7e6473fba0655de4f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketClient.js @@ -0,0 +1,348 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var utils = require('./utils'); +var extend = utils.extend; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +var http = require('http'); +var https = require('https'); +var url = require('url'); +var crypto = require('crypto'); +var WebSocketConnection = require('./WebSocketConnection'); + +var protocolSeparators = [ + '(', ')', '<', '>', '@', + ',', ';', ':', '\\', '\"', + '/', '[', ']', '?', '=', + '{', '}', ' ', String.fromCharCode(9) +]; + +function WebSocketClient(config) { + // Superclass Constructor + EventEmitter.call(this); + + // TODO: Implement extensions + + this.config = { + // 1MiB max frame size. + maxReceivedFrameSize: 0x100000, + + // 8MiB max message size, only applicable if + // assembleFragments is true + maxReceivedMessageSize: 0x800000, + + // Outgoing messages larger than fragmentationThreshold will be + // split into multiple fragments. + fragmentOutgoingMessages: true, + + // Outgoing frames are fragmented if they exceed this threshold. + // Default is 16KiB + fragmentationThreshold: 0x4000, + + // Which version of the protocol to use for this session. This + // option will be removed once the protocol is finalized by the IETF + // It is only available to ease the transition through the + // intermediate draft protocol versions. + // At present, it only affects the name of the Origin header. + webSocketVersion: 13, + + // If true, fragmented messages will be automatically assembled + // and the full message will be emitted via a 'message' event. + // If false, each frame will be emitted via a 'frame' event and + // the application will be responsible for aggregating multiple + // fragmented frames. Single-frame messages will emit a 'message' + // event in addition to the 'frame' event. + // Most users will want to leave this set to 'true' + assembleFragments: true, + + // The Nagle Algorithm makes more efficient use of network resources + // by introducing a small delay before sending small packets so that + // multiple messages can be batched together before going onto the + // wire. This however comes at the cost of latency, so the default + // is to disable it. If you don't need low latency and are streaming + // lots of small messages, you can change this to 'false' + disableNagleAlgorithm: true, + + // The number of milliseconds to wait after sending a close frame + // for an acknowledgement to come back before giving up and just + // closing the socket. + closeTimeout: 5000, + + // Options to pass to https.connect if connecting via TLS + tlsOptions: {} + }; + + if (config) { + var tlsOptions; + if (config.tlsOptions) { + tlsOptions = config.tlsOptions; + delete config.tlsOptions; + } + else { + tlsOptions = {}; + } + extend(this.config, config); + extend(this.config.tlsOptions, tlsOptions); + } + + this._req = null; + + switch (this.config.webSocketVersion) { + case 8: + case 13: + break; + default: + throw new Error('Requested webSocketVersion is not supported. Allowed values are 8 and 13.'); + } +} + +util.inherits(WebSocketClient, EventEmitter); + +WebSocketClient.prototype.connect = function(requestUrl, protocols, origin, headers, extraRequestOptions) { + var self = this; + if (typeof(protocols) === 'string') { + if (protocols.length > 0) { + protocols = [protocols]; + } + else { + protocols = []; + } + } + if (!(protocols instanceof Array)) { + protocols = []; + } + this.protocols = protocols; + this.origin = origin; + + if (typeof(requestUrl) === 'string') { + this.url = url.parse(requestUrl); + } + else { + this.url = requestUrl; // in case an already parsed url is passed in. + } + if (!this.url.protocol) { + throw new Error('You must specify a full WebSocket URL, including protocol.'); + } + if (!this.url.host) { + throw new Error('You must specify a full WebSocket URL, including hostname. Relative URLs are not supported.'); + } + + this.secure = (this.url.protocol === 'wss:'); + + // validate protocol characters: + this.protocols.forEach(function(protocol) { + for (var i=0; i < protocol.length; i ++) { + var charCode = protocol.charCodeAt(i); + var character = protocol.charAt(i); + if (charCode < 0x0021 || charCode > 0x007E || protocolSeparators.indexOf(character) !== -1) { + throw new Error('Protocol list contains invalid character "' + String.fromCharCode(charCode) + '"'); + } + } + }); + + var defaultPorts = { + 'ws:': '80', + 'wss:': '443' + }; + + if (!this.url.port) { + this.url.port = defaultPorts[this.url.protocol]; + } + + var nonce = new Buffer(16); + for (var i=0; i < 16; i++) { + nonce[i] = Math.round(Math.random()*0xFF); + } + this.base64nonce = nonce.toString('base64'); + + var hostHeaderValue = this.url.hostname; + if ((this.url.protocol === 'ws:' && this.url.port !== '80') || + (this.url.protocol === 'wss:' && this.url.port !== '443')) { + hostHeaderValue += (':' + this.url.port); + } + + var reqHeaders = headers || {}; + extend(reqHeaders, { + 'Upgrade': 'websocket', + 'Connection': 'Upgrade', + 'Sec-WebSocket-Version': this.config.webSocketVersion.toString(10), + 'Sec-WebSocket-Key': this.base64nonce, + 'Host': reqHeaders.Host || hostHeaderValue + }); + + if (this.protocols.length > 0) { + reqHeaders['Sec-WebSocket-Protocol'] = this.protocols.join(', '); + } + if (this.origin) { + if (this.config.webSocketVersion === 13) { + reqHeaders['Origin'] = this.origin; + } + else if (this.config.webSocketVersion === 8) { + reqHeaders['Sec-WebSocket-Origin'] = this.origin; + } + } + + // TODO: Implement extensions + + var pathAndQuery; + // Ensure it begins with '/'. + if (this.url.pathname) { + pathAndQuery = this.url.path; + } + else if (this.url.path) { + pathAndQuery = '/' + this.url.path; + } + else { + pathAndQuery = '/'; + } + + function handleRequestError(error) { + self._req = null; + self.emit('connectFailed', error); + } + + var requestOptions = { + agent: false + }; + if (extraRequestOptions) { + extend(requestOptions, extraRequestOptions); + } + // These options are always overridden by the library. The user is not + // allowed to specify these directly. + extend(requestOptions, { + hostname: this.url.hostname, + port: this.url.port, + method: 'GET', + path: pathAndQuery, + headers: reqHeaders + }); + if (this.secure) { + for (var key in self.config.tlsOptions) { + if (self.config.tlsOptions.hasOwnProperty(key)) { + requestOptions[key] = self.config.tlsOptions[key]; + } + } + } + + var req = this._req = (this.secure ? https : http).request(requestOptions); + req.on('upgrade', function handleRequestUpgrade(response, socket, head) { + self._req = null; + req.removeListener('error', handleRequestError); + self.socket = socket; + self.response = response; + self.firstDataChunk = head; + self.validateHandshake(); + }); + req.on('error', handleRequestError); + + req.on('response', function(response) { + self._req = null; + if (utils.eventEmitterListenerCount(self, 'httpResponse') > 0) { + self.emit('httpResponse', response, self); + if (response.socket) { + response.socket.end(); + } + } + else { + var headerDumpParts = []; + for (var headerName in response.headers) { + headerDumpParts.push(headerName + ': ' + response.headers[headerName]); + } + self.failHandshake( + 'Server responded with a non-101 status: ' + + response.statusCode + ' ' + response.statusMessage + + '\nResponse Headers Follow:\n' + + headerDumpParts.join('\n') + '\n' + ); + } + }); + req.end(); +}; + +WebSocketClient.prototype.validateHandshake = function() { + var headers = this.response.headers; + + if (this.protocols.length > 0) { + this.protocol = headers['sec-websocket-protocol']; + if (this.protocol) { + if (this.protocols.indexOf(this.protocol) === -1) { + this.failHandshake('Server did not respond with a requested protocol.'); + return; + } + } + else { + this.failHandshake('Expected a Sec-WebSocket-Protocol header.'); + return; + } + } + + if (!(headers['connection'] && headers['connection'].toLocaleLowerCase() === 'upgrade')) { + this.failHandshake('Expected a Connection: Upgrade header from the server'); + return; + } + + if (!(headers['upgrade'] && headers['upgrade'].toLocaleLowerCase() === 'websocket')) { + this.failHandshake('Expected an Upgrade: websocket header from the server'); + return; + } + + var sha1 = crypto.createHash('sha1'); + sha1.update(this.base64nonce + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); + var expectedKey = sha1.digest('base64'); + + if (!headers['sec-websocket-accept']) { + this.failHandshake('Expected Sec-WebSocket-Accept header from server'); + return; + } + + if (headers['sec-websocket-accept'] !== expectedKey) { + this.failHandshake('Sec-WebSocket-Accept header from server didn\'t match expected value of ' + expectedKey); + return; + } + + // TODO: Support extensions + + this.succeedHandshake(); +}; + +WebSocketClient.prototype.failHandshake = function(errorDescription) { + if (this.socket && this.socket.writable) { + this.socket.end(); + } + this.emit('connectFailed', new Error(errorDescription)); +}; + +WebSocketClient.prototype.succeedHandshake = function() { + var connection = new WebSocketConnection(this.socket, [], this.protocol, true, this.config); + + connection.webSocketVersion = this.config.webSocketVersion; + connection._addSocketEventListeners(); + + this.emit('connect', connection); + if (this.firstDataChunk.length > 0) { + connection.handleSocketData(this.firstDataChunk); + } + this.firstDataChunk = null; +}; + +WebSocketClient.prototype.abort = function() { + if (this._req) { + this._req.abort(); + } +}; + +module.exports = WebSocketClient; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketConnection.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketConnection.js new file mode 100644 index 0000000000000000000000000000000000000000..2c19aab9c5b940db173ce3388a1d058ba86fb7cb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketConnection.js @@ -0,0 +1,894 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var util = require('util'); +var utils = require('./utils'); +var EventEmitter = require('events').EventEmitter; +var WebSocketFrame = require('./WebSocketFrame'); +var BufferList = require('../vendor/FastBufferList'); +var Validation = require('./Validation').Validation; + +// Connected, fully-open, ready to send and receive frames +const STATE_OPEN = 'open'; +// Received a close frame from the remote peer +const STATE_PEER_REQUESTED_CLOSE = 'peer_requested_close'; +// Sent close frame to remote peer. No further data can be sent. +const STATE_ENDING = 'ending'; +// Connection is fully closed. No further data can be sent or received. +const STATE_CLOSED = 'closed'; + +var setImmediateImpl = ('setImmediate' in global) ? + global.setImmediate.bind(global) : + process.nextTick.bind(process); + +var idCounter = 0; + +function WebSocketConnection(socket, extensions, protocol, maskOutgoingPackets, config) { + this._debug = utils.BufferingLogger('websocket:connection', ++idCounter); + this._debug('constructor'); + + if (this._debug.enabled) { + instrumentSocketForDebugging(this, socket); + } + + // Superclass Constructor + EventEmitter.call(this); + + this._pingListenerCount = 0; + this.on('newListener', function(ev) { + if (ev === 'ping'){ + this._pingListenerCount++; + } + }).on('removeListener', function(ev) { + if (ev === 'ping') { + this._pingListenerCount--; + } + }); + + this.config = config; + this.socket = socket; + this.protocol = protocol; + this.extensions = extensions; + this.remoteAddress = socket.remoteAddress; + this.closeReasonCode = -1; + this.closeDescription = null; + this.closeEventEmitted = false; + + // We have to mask outgoing packets if we're acting as a WebSocket client. + this.maskOutgoingPackets = maskOutgoingPackets; + + // We re-use the same buffers for the mask and frame header for all frames + // received on each connection to avoid a small memory allocation for each + // frame. + this.maskBytes = new Buffer(4); + this.frameHeader = new Buffer(10); + + // the BufferList will handle the data streaming in + this.bufferList = new BufferList(); + + // Prepare for receiving first frame + this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + this.fragmentationSize = 0; // data received so far... + this.frameQueue = []; + + // Various bits of connection state + this.connected = true; + this.state = STATE_OPEN; + this.waitingForCloseResponse = false; + // Received TCP FIN, socket's readable stream is finished. + this.receivedEnd = false; + + this.closeTimeout = this.config.closeTimeout; + this.assembleFragments = this.config.assembleFragments; + this.maxReceivedMessageSize = this.config.maxReceivedMessageSize; + + this.outputBufferFull = false; + this.inputPaused = false; + this.receivedDataHandler = this.processReceivedData.bind(this); + this._closeTimerHandler = this.handleCloseTimer.bind(this); + + // Disable nagle algorithm? + this.socket.setNoDelay(this.config.disableNagleAlgorithm); + + // Make sure there is no socket inactivity timeout + this.socket.setTimeout(0); + + if (this.config.keepalive && !this.config.useNativeKeepalive) { + if (typeof(this.config.keepaliveInterval) !== 'number') { + throw new Error('keepaliveInterval must be specified and numeric ' + + 'if keepalive is true.'); + } + this._keepaliveTimerHandler = this.handleKeepaliveTimer.bind(this); + this.setKeepaliveTimer(); + + if (this.config.dropConnectionOnKeepaliveTimeout) { + if (typeof(this.config.keepaliveGracePeriod) !== 'number') { + throw new Error('keepaliveGracePeriod must be specified and ' + + 'numeric if dropConnectionOnKeepaliveTimeout ' + + 'is true.'); + } + this._gracePeriodTimerHandler = this.handleGracePeriodTimer.bind(this); + } + } + else if (this.config.keepalive && this.config.useNativeKeepalive) { + if (!('setKeepAlive' in this.socket)) { + throw new Error('Unable to use native keepalive: unsupported by ' + + 'this version of Node.'); + } + this.socket.setKeepAlive(true, this.config.keepaliveInterval); + } + + // The HTTP Client seems to subscribe to socket error events + // and re-dispatch them in such a way that doesn't make sense + // for users of our client, so we want to make sure nobody + // else is listening for error events on the socket besides us. + this.socket.removeAllListeners('error'); +} + +WebSocketConnection.CLOSE_REASON_NORMAL = 1000; +WebSocketConnection.CLOSE_REASON_GOING_AWAY = 1001; +WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR = 1002; +WebSocketConnection.CLOSE_REASON_UNPROCESSABLE_INPUT = 1003; +WebSocketConnection.CLOSE_REASON_RESERVED = 1004; // Reserved value. Undefined meaning. +WebSocketConnection.CLOSE_REASON_NOT_PROVIDED = 1005; // Not to be used on the wire +WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006; // Not to be used on the wire +WebSocketConnection.CLOSE_REASON_INVALID_DATA = 1007; +WebSocketConnection.CLOSE_REASON_POLICY_VIOLATION = 1008; +WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG = 1009; +WebSocketConnection.CLOSE_REASON_EXTENSION_REQUIRED = 1010; +WebSocketConnection.CLOSE_REASON_INTERNAL_SERVER_ERROR = 1011; +WebSocketConnection.CLOSE_REASON_TLS_HANDSHAKE_FAILED = 1015; // Not to be used on the wire + +WebSocketConnection.CLOSE_DESCRIPTIONS = { + 1000: 'Normal connection closure', + 1001: 'Remote peer is going away', + 1002: 'Protocol error', + 1003: 'Unprocessable input', + 1004: 'Reserved', + 1005: 'Reason not provided', + 1006: 'Abnormal closure, no further detail available', + 1007: 'Invalid data received', + 1008: 'Policy violation', + 1009: 'Message too big', + 1010: 'Extension requested by client is required', + 1011: 'Internal Server Error', + 1015: 'TLS Handshake Failed' +}; + +function validateCloseReason(code) { + if (code < 1000) { + // Status codes in the range 0-999 are not used + return false; + } + if (code >= 1000 && code <= 2999) { + // Codes from 1000 - 2999 are reserved for use by the protocol. Only + // a few codes are defined, all others are currently illegal. + return [1000, 1001, 1002, 1003, 1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014].indexOf(code) !== -1; + } + if (code >= 3000 && code <= 3999) { + // Reserved for use by libraries, frameworks, and applications. + // Should be registered with IANA. Interpretation of these codes is + // undefined by the WebSocket protocol. + return true; + } + if (code >= 4000 && code <= 4999) { + // Reserved for private use. Interpretation of these codes is + // undefined by the WebSocket protocol. + return true; + } + if (code >= 5000) { + return false; + } +} + +util.inherits(WebSocketConnection, EventEmitter); + +WebSocketConnection.prototype._addSocketEventListeners = function() { + this.socket.on('error', this.handleSocketError.bind(this)); + this.socket.on('end', this.handleSocketEnd.bind(this)); + this.socket.on('close', this.handleSocketClose.bind(this)); + this.socket.on('drain', this.handleSocketDrain.bind(this)); + this.socket.on('pause', this.handleSocketPause.bind(this)); + this.socket.on('resume', this.handleSocketResume.bind(this)); + this.socket.on('data', this.handleSocketData.bind(this)); +}; + +// set or reset the keepalive timer when data is received. +WebSocketConnection.prototype.setKeepaliveTimer = function() { + this._debug('setKeepaliveTimer'); + if (!this.config.keepalive || this.config.useNativeKeepalive) { return; } + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + this._keepaliveTimeoutID = setTimeout(this._keepaliveTimerHandler, this.config.keepaliveInterval); +}; + +WebSocketConnection.prototype.clearKeepaliveTimer = function() { + if (this._keepaliveTimeoutID) { + clearTimeout(this._keepaliveTimeoutID); + } +}; + +// No data has been received within config.keepaliveTimeout ms. +WebSocketConnection.prototype.handleKeepaliveTimer = function() { + this._debug('handleKeepaliveTimer'); + this._keepaliveTimeoutID = null; + this.ping(); + + // If we are configured to drop connections if the client doesn't respond + // then set the grace period timer. + if (this.config.dropConnectionOnKeepaliveTimeout) { + this.setGracePeriodTimer(); + } + else { + // Otherwise reset the keepalive timer to send the next ping. + this.setKeepaliveTimer(); + } +}; + +WebSocketConnection.prototype.setGracePeriodTimer = function() { + this._debug('setGracePeriodTimer'); + this.clearGracePeriodTimer(); + this._gracePeriodTimeoutID = setTimeout(this._gracePeriodTimerHandler, this.config.keepaliveGracePeriod); +}; + +WebSocketConnection.prototype.clearGracePeriodTimer = function() { + if (this._gracePeriodTimeoutID) { + clearTimeout(this._gracePeriodTimeoutID); + } +}; + +WebSocketConnection.prototype.handleGracePeriodTimer = function() { + this._debug('handleGracePeriodTimer'); + // If this is called, the client has not responded and is assumed dead. + this._gracePeriodTimeoutID = null; + this.drop(WebSocketConnection.CLOSE_REASON_ABNORMAL, 'Peer not responding.', true); +}; + +WebSocketConnection.prototype.handleSocketData = function(data) { + this._debug('handleSocketData'); + // Reset the keepalive timer when receiving data of any kind. + this.setKeepaliveTimer(); + + // Add received data to our bufferList, which efficiently holds received + // data chunks in a linked list of Buffer objects. + this.bufferList.write(data); + + this.processReceivedData(); +}; + +WebSocketConnection.prototype.processReceivedData = function() { + this._debug('processReceivedData'); + // If we're not connected, we should ignore any data remaining on the buffer. + if (!this.connected) { return; } + + // Receiving/parsing is expected to be halted when paused. + if (this.inputPaused) { return; } + + var frame = this.currentFrame; + + // WebSocketFrame.prototype.addData returns true if all data necessary to + // parse the frame was available. It returns false if we are waiting for + // more data to come in on the wire. + if (!frame.addData(this.bufferList)) { this._debug('-- insufficient data for frame'); return; } + + var self = this; + + // Handle possible parsing errors + if (frame.protocolError) { + // Something bad happened.. get rid of this client. + this._debug('-- protocol error'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, frame.dropReason); + }); + return; + } + else if (frame.frameTooLarge) { + this._debug('-- frame too large'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, frame.dropReason); + }); + return; + } + + // For now since we don't support extensions, all RSV bits are illegal + if (frame.rsv1 || frame.rsv2 || frame.rsv3) { + this._debug('-- illegal rsv flag'); + process.nextTick(function() { + self.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unsupported usage of rsv bits without negotiated extension.'); + }); + return; + } + + if (!this.assembleFragments) { + this._debug('-- emitting frame'); + process.nextTick(function() { self.emit('frame', frame); }); + } + + process.nextTick(function() { self.processFrame(frame); }); + + this.currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + + // If there's data remaining, schedule additional processing, but yield + // for now so that other connections have a chance to have their data + // processed. We use setImmediate here instead of process.nextTick to + // explicitly indicate that we wish for other I/O to be handled first. + if (this.bufferList.length > 0) { + setImmediateImpl(this.receivedDataHandler); + } +}; + +WebSocketConnection.prototype.handleSocketError = function(error) { + this._debug('handleSocketError: %j', error); + if (this.state === STATE_CLOSED) { + // See https://github.com/theturtle32/WebSocket-Node/issues/288 + this._debug(' --- Socket \'error\' after \'close\''); + return; + } + this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL; + this.closeDescription = 'Socket Error: ' + error.syscall + ' ' + error.code; + this.connected = false; + this.state = STATE_CLOSED; + this.fragmentationSize = 0; + if (utils.eventEmitterListenerCount(this, 'error') > 0) { + this.emit('error', error); + } + this.socket.destroy(error); + this._debug.printOutput(); +}; + +WebSocketConnection.prototype.handleSocketEnd = function() { + this._debug('handleSocketEnd: received socket end. state = %s', this.state); + this.receivedEnd = true; + if (this.state === STATE_CLOSED) { + // When using the TLS module, sometimes the socket will emit 'end' + // after it emits 'close'. I don't think that's correct behavior, + // but we should deal with it gracefully by ignoring it. + this._debug(' --- Socket \'end\' after \'close\''); + return; + } + if (this.state !== STATE_PEER_REQUESTED_CLOSE && + this.state !== STATE_ENDING) { + this._debug(' --- UNEXPECTED socket end.'); + this.socket.end(); + } +}; + +WebSocketConnection.prototype.handleSocketClose = function(hadError) { + this._debug('handleSocketClose: received socket close'); + this.socketHadError = hadError; + this.connected = false; + this.state = STATE_CLOSED; + // If closeReasonCode is still set to -1 at this point then we must + // not have received a close frame!! + if (this.closeReasonCode === -1) { + this.closeReasonCode = WebSocketConnection.CLOSE_REASON_ABNORMAL; + this.closeDescription = 'Connection dropped by remote peer.'; + } + this.clearCloseTimer(); + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + if (!this.closeEventEmitted) { + this.closeEventEmitted = true; + this._debug('-- Emitting WebSocketConnection close event'); + this.emit('close', this.closeReasonCode, this.closeDescription); + } +}; + +WebSocketConnection.prototype.handleSocketDrain = function() { + this._debug('handleSocketDrain: socket drain event'); + this.outputBufferFull = false; + this.emit('drain'); +}; + +WebSocketConnection.prototype.handleSocketPause = function() { + this._debug('handleSocketPause: socket pause event'); + this.inputPaused = true; + this.emit('pause'); +}; + +WebSocketConnection.prototype.handleSocketResume = function() { + this._debug('handleSocketResume: socket resume event'); + this.inputPaused = false; + this.emit('resume'); + this.processReceivedData(); +}; + +WebSocketConnection.prototype.pause = function() { + this._debug('pause: pause requested'); + this.socket.pause(); +}; + +WebSocketConnection.prototype.resume = function() { + this._debug('resume: resume requested'); + this.socket.resume(); +}; + +WebSocketConnection.prototype.close = function(reasonCode, description) { + if (this.connected) { + this._debug('close: Initating clean WebSocket close sequence.'); + if ('number' !== typeof reasonCode) { + reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + if (!validateCloseReason(reasonCode)) { + throw new Error('Close code ' + reasonCode + ' is not valid.'); + } + if ('string' !== typeof description) { + description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode]; + } + this.closeReasonCode = reasonCode; + this.closeDescription = description; + this.setCloseTimer(); + this.sendCloseFrame(this.closeReasonCode, this.closeDescription); + this.state = STATE_ENDING; + this.connected = false; + } +}; + +WebSocketConnection.prototype.drop = function(reasonCode, description, skipCloseFrame) { + this._debug('drop'); + if (typeof(reasonCode) !== 'number') { + reasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + + if (typeof(description) !== 'string') { + // If no description is provided, try to look one up based on the + // specified reasonCode. + description = WebSocketConnection.CLOSE_DESCRIPTIONS[reasonCode]; + } + + this._debug('Forcefully dropping connection. skipCloseFrame: %s, code: %d, description: %s', + skipCloseFrame, reasonCode, description + ); + + this.closeReasonCode = reasonCode; + this.closeDescription = description; + this.frameQueue = []; + this.fragmentationSize = 0; + if (!skipCloseFrame) { + this.sendCloseFrame(reasonCode, description); + } + this.connected = false; + this.state = STATE_CLOSED; + this.clearCloseTimer(); + this.clearKeepaliveTimer(); + this.clearGracePeriodTimer(); + + if (!this.closeEventEmitted) { + this.closeEventEmitted = true; + this._debug('Emitting WebSocketConnection close event'); + this.emit('close', this.closeReasonCode, this.closeDescription); + } + + this._debug('Drop: destroying socket'); + this.socket.destroy(); +}; + +WebSocketConnection.prototype.setCloseTimer = function() { + this._debug('setCloseTimer'); + this.clearCloseTimer(); + this._debug('Setting close timer'); + this.waitingForCloseResponse = true; + this.closeTimer = setTimeout(this._closeTimerHandler, this.closeTimeout); +}; + +WebSocketConnection.prototype.clearCloseTimer = function() { + this._debug('clearCloseTimer'); + if (this.closeTimer) { + this._debug('Clearing close timer'); + clearTimeout(this.closeTimer); + this.waitingForCloseResponse = false; + this.closeTimer = null; + } +}; + +WebSocketConnection.prototype.handleCloseTimer = function() { + this._debug('handleCloseTimer'); + this.closeTimer = null; + if (this.waitingForCloseResponse) { + this._debug('Close response not received from client. Forcing socket end.'); + this.waitingForCloseResponse = false; + this.state = STATE_CLOSED; + this.socket.end(); + } +}; + +WebSocketConnection.prototype.processFrame = function(frame) { + this._debug('processFrame'); + this._debug(' -- frame: %s', frame); + + // Any non-control opcode besides 0x00 (continuation) received in the + // middle of a fragmented message is illegal. + if (this.frameQueue.length !== 0 && (frame.opcode > 0x00 && frame.opcode < 0x08)) { + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Illegal frame opcode 0x' + frame.opcode.toString(16) + ' ' + + 'received in middle of fragmented message.'); + return; + } + + switch(frame.opcode) { + case 0x02: // WebSocketFrame.BINARY_FRAME + this._debug('-- Binary Frame'); + if (this.assembleFragments) { + if (frame.fin) { + // Complete single-frame message received + this._debug('---- Emitting \'message\' event'); + this.emit('message', { + type: 'binary', + binaryData: frame.binaryPayload + }); + } + else { + // beginning of a fragmented message + this.frameQueue.push(frame); + this.fragmentationSize = frame.length; + } + } + break; + case 0x01: // WebSocketFrame.TEXT_FRAME + this._debug('-- Text Frame'); + if (this.assembleFragments) { + if (frame.fin) { + if (!Validation.isValidUTF8(frame.binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + // Complete single-frame message received + this._debug('---- Emitting \'message\' event'); + this.emit('message', { + type: 'utf8', + utf8Data: frame.binaryPayload.toString('utf8') + }); + } + else { + // beginning of a fragmented message + this.frameQueue.push(frame); + this.fragmentationSize = frame.length; + } + } + break; + case 0x00: // WebSocketFrame.CONTINUATION + this._debug('-- Continuation Frame'); + if (this.assembleFragments) { + if (this.frameQueue.length === 0) { + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unexpected Continuation Frame'); + return; + } + + this.fragmentationSize += frame.length; + + if (this.fragmentationSize > this.maxReceivedMessageSize) { + this.drop(WebSocketConnection.CLOSE_REASON_MESSAGE_TOO_BIG, + 'Maximum message size exceeded.'); + return; + } + + this.frameQueue.push(frame); + + if (frame.fin) { + // end of fragmented message, so we process the whole + // message now. We also have to decode the utf-8 data + // for text frames after combining all the fragments. + var bytesCopied = 0; + var binaryPayload = new Buffer(this.fragmentationSize); + var opcode = this.frameQueue[0].opcode; + this.frameQueue.forEach(function (currentFrame) { + currentFrame.binaryPayload.copy(binaryPayload, bytesCopied); + bytesCopied += currentFrame.binaryPayload.length; + }); + this.frameQueue = []; + this.fragmentationSize = 0; + + switch (opcode) { + case 0x02: // WebSocketOpcode.BINARY_FRAME + this.emit('message', { + type: 'binary', + binaryData: binaryPayload + }); + break; + case 0x01: // WebSocketOpcode.TEXT_FRAME + if (!Validation.isValidUTF8(binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + this.emit('message', { + type: 'utf8', + utf8Data: binaryPayload.toString('utf8') + }); + break; + default: + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unexpected first opcode in fragmentation sequence: 0x' + opcode.toString(16)); + return; + } + } + } + break; + case 0x09: // WebSocketFrame.PING + this._debug('-- Ping Frame'); + + if (this._pingListenerCount > 0) { + // logic to emit the ping frame: this is only done when a listener is known to exist + // Expose a function allowing the user to override the default ping() behavior + var cancelled = false; + var cancel = function() { + cancelled = true; + }; + this.emit('ping', cancel, frame.binaryPayload); + + // Only send a pong if the client did not indicate that he would like to cancel + if (!cancelled) { + this.pong(frame.binaryPayload); + } + } + else { + this.pong(frame.binaryPayload); + } + + break; + case 0x0A: // WebSocketFrame.PONG + this._debug('-- Pong Frame'); + this.emit('pong', frame.binaryPayload); + break; + case 0x08: // WebSocketFrame.CONNECTION_CLOSE + this._debug('-- Close Frame'); + if (this.waitingForCloseResponse) { + // Got response to our request to close the connection. + // Close is complete, so we just hang up. + this._debug('---- Got close response from peer. Completing closing handshake.'); + this.clearCloseTimer(); + this.waitingForCloseResponse = false; + this.state = STATE_CLOSED; + this.socket.end(); + return; + } + + this._debug('---- Closing handshake initiated by peer.'); + // Got request from other party to close connection. + // Send back acknowledgement and then hang up. + this.state = STATE_PEER_REQUESTED_CLOSE; + var respondCloseReasonCode; + + // Make sure the close reason provided is legal according to + // the protocol spec. Providing no close status is legal. + // WebSocketFrame sets closeStatus to -1 by default, so if it + // is still -1, then no status was provided. + if (frame.invalidCloseFrameLength) { + this.closeReasonCode = 1005; // 1005 = No reason provided. + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + else if (frame.closeStatus === -1 || validateCloseReason(frame.closeStatus)) { + this.closeReasonCode = frame.closeStatus; + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + else { + this.closeReasonCode = frame.closeStatus; + respondCloseReasonCode = WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR; + } + + // If there is a textual description in the close frame, extract it. + if (frame.binaryPayload.length > 1) { + if (!Validation.isValidUTF8(frame.binaryPayload)) { + this.drop(WebSocketConnection.CLOSE_REASON_INVALID_DATA, + 'Invalid UTF-8 Data Received'); + return; + } + this.closeDescription = frame.binaryPayload.toString('utf8'); + } + else { + this.closeDescription = WebSocketConnection.CLOSE_DESCRIPTIONS[this.closeReasonCode]; + } + this._debug( + '------ Remote peer %s - code: %d - %s - close frame payload length: %d', + this.remoteAddress, this.closeReasonCode, + this.closeDescription, frame.length + ); + this._debug('------ responding to remote peer\'s close request.'); + this.sendCloseFrame(respondCloseReasonCode, null); + this.connected = false; + break; + default: + this._debug('-- Unrecognized Opcode %d', frame.opcode); + this.drop(WebSocketConnection.CLOSE_REASON_PROTOCOL_ERROR, + 'Unrecognized Opcode: 0x' + frame.opcode.toString(16)); + break; + } +}; + +WebSocketConnection.prototype.send = function(data, cb) { + this._debug('send'); + if (Buffer.isBuffer(data)) { + this.sendBytes(data, cb); + } + else if (typeof(data['toString']) === 'function') { + this.sendUTF(data, cb); + } + else { + throw new Error('Data provided must either be a Node Buffer or implement toString()'); + } +}; + +WebSocketConnection.prototype.sendUTF = function(data, cb) { + data = new Buffer(data.toString(), 'utf8'); + this._debug('sendUTF: %d bytes', data.length); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x01; // WebSocketOpcode.TEXT_FRAME + frame.binaryPayload = data; + this.fragmentAndSend(frame, cb); +}; + +WebSocketConnection.prototype.sendBytes = function(data, cb) { + this._debug('sendBytes'); + if (!Buffer.isBuffer(data)) { + throw new Error('You must pass a Node Buffer object to WebSocketConnection.prototype.sendBytes()'); + } + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x02; // WebSocketOpcode.BINARY_FRAME + frame.binaryPayload = data; + this.fragmentAndSend(frame, cb); +}; + +WebSocketConnection.prototype.ping = function(data) { + this._debug('ping'); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x09; // WebSocketOpcode.PING + frame.fin = true; + if (data) { + if (!Buffer.isBuffer(data)) { + data = new Buffer(data.toString(), 'utf8'); + } + if (data.length > 125) { + this._debug('WebSocket: Data for ping is longer than 125 bytes. Truncating.'); + data = data.slice(0,124); + } + frame.binaryPayload = data; + } + this.sendFrame(frame); +}; + +// Pong frames have to echo back the contents of the data portion of the +// ping frame exactly, byte for byte. +WebSocketConnection.prototype.pong = function(binaryPayload) { + this._debug('pong'); + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.opcode = 0x0A; // WebSocketOpcode.PONG + if (Buffer.isBuffer(binaryPayload) && binaryPayload.length > 125) { + this._debug('WebSocket: Data for pong is longer than 125 bytes. Truncating.'); + binaryPayload = binaryPayload.slice(0,124); + } + frame.binaryPayload = binaryPayload; + frame.fin = true; + this.sendFrame(frame); +}; + +WebSocketConnection.prototype.fragmentAndSend = function(frame, cb) { + this._debug('fragmentAndSend'); + if (frame.opcode > 0x07) { + throw new Error('You cannot fragment control frames.'); + } + + var threshold = this.config.fragmentationThreshold; + var length = frame.binaryPayload.length; + + // Send immediately if fragmentation is disabled or the message is not + // larger than the fragmentation threshold. + if (!this.config.fragmentOutgoingMessages || (frame.binaryPayload && length <= threshold)) { + frame.fin = true; + this.sendFrame(frame, cb); + return; + } + + var numFragments = Math.ceil(length / threshold); + var sentFragments = 0; + var sentCallback = function fragmentSentCallback(err) { + if (err) { + if (typeof cb === 'function') { + // pass only the first error + cb(err); + cb = null; + } + return; + } + ++sentFragments; + if ((sentFragments === numFragments) && (typeof cb === 'function')) { + cb(); + } + }; + for (var i=1; i <= numFragments; i++) { + var currentFrame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + + // continuation opcode except for first frame. + currentFrame.opcode = (i === 1) ? frame.opcode : 0x00; + + // fin set on last frame only + currentFrame.fin = (i === numFragments); + + // length is likely to be shorter on the last fragment + var currentLength = (i === numFragments) ? length - (threshold * (i-1)) : threshold; + var sliceStart = threshold * (i-1); + + // Slice the right portion of the original payload + currentFrame.binaryPayload = frame.binaryPayload.slice(sliceStart, sliceStart + currentLength); + + this.sendFrame(currentFrame, sentCallback); + } +}; + +WebSocketConnection.prototype.sendCloseFrame = function(reasonCode, description, cb) { + if (typeof(reasonCode) !== 'number') { + reasonCode = WebSocketConnection.CLOSE_REASON_NORMAL; + } + + this._debug('sendCloseFrame state: %s, reasonCode: %d, description: %s', this.state, reasonCode, description); + + if (this.state !== STATE_OPEN && this.state !== STATE_PEER_REQUESTED_CLOSE) { return; } + + var frame = new WebSocketFrame(this.maskBytes, this.frameHeader, this.config); + frame.fin = true; + frame.opcode = 0x08; // WebSocketOpcode.CONNECTION_CLOSE + frame.closeStatus = reasonCode; + if (typeof(description) === 'string') { + frame.binaryPayload = new Buffer(description, 'utf8'); + } + + this.sendFrame(frame, cb); + this.socket.end(); +}; + +WebSocketConnection.prototype.sendFrame = function(frame, cb) { + this._debug('sendFrame'); + frame.mask = this.maskOutgoingPackets; + var flushed = this.socket.write(frame.toBuffer(), cb); + this.outputBufferFull = !flushed; + return flushed; +}; + +module.exports = WebSocketConnection; + + + +function instrumentSocketForDebugging(connection, socket) { + /* jshint loopfunc: true */ + if (!connection._debug.enabled) { return; } + + var originalSocketEmit = socket.emit; + socket.emit = function(event) { + connection._debug('||| Socket Event \'%s\'', event); + originalSocketEmit.apply(this, arguments); + }; + + for (var key in socket) { + if ('function' !== typeof(socket[key])) { continue; } + if (['emit'].indexOf(key) !== -1) { continue; } + (function(key) { + var original = socket[key]; + if (key === 'on') { + socket[key] = function proxyMethod__EventEmitter__On() { + connection._debug('||| Socket method called: %s (%s)', key, arguments[0]); + return original.apply(this, arguments); + }; + return; + } + socket[key] = function proxyMethod() { + connection._debug('||| Socket method called: %s', key); + return original.apply(this, arguments); + }; + })(key); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketFrame.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketFrame.js new file mode 100644 index 0000000000000000000000000000000000000000..859e8797d3ae7cd4998fe121df12d399099dcfc2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketFrame.js @@ -0,0 +1,279 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var bufferUtil = require('./BufferUtil').BufferUtil; + +const DECODE_HEADER = 1; +const WAITING_FOR_16_BIT_LENGTH = 2; +const WAITING_FOR_64_BIT_LENGTH = 3; +const WAITING_FOR_MASK_KEY = 4; +const WAITING_FOR_PAYLOAD = 5; +const COMPLETE = 6; + +// WebSocketConnection will pass shared buffer objects for maskBytes and +// frameHeader into the constructor to avoid tons of small memory allocations +// for each frame we have to parse. This is only used for parsing frames +// we receive off the wire. +function WebSocketFrame(maskBytes, frameHeader, config) { + this.maskBytes = maskBytes; + this.frameHeader = frameHeader; + this.config = config; + this.maxReceivedFrameSize = config.maxReceivedFrameSize; + this.protocolError = false; + this.frameTooLarge = false; + this.invalidCloseFrameLength = false; + this.parseState = DECODE_HEADER; + this.closeStatus = -1; +} + +WebSocketFrame.prototype.addData = function(bufferList) { + if (this.parseState === DECODE_HEADER) { + if (bufferList.length >= 2) { + bufferList.joinInto(this.frameHeader, 0, 0, 2); + bufferList.advance(2); + var firstByte = this.frameHeader[0]; + var secondByte = this.frameHeader[1]; + + this.fin = Boolean(firstByte & 0x80); + this.rsv1 = Boolean(firstByte & 0x40); + this.rsv2 = Boolean(firstByte & 0x20); + this.rsv3 = Boolean(firstByte & 0x10); + this.mask = Boolean(secondByte & 0x80); + + this.opcode = firstByte & 0x0F; + this.length = secondByte & 0x7F; + + // Control frame sanity check + if (this.opcode >= 0x08) { + if (this.length > 125) { + this.protocolError = true; + this.dropReason = 'Illegal control frame longer than 125 bytes.'; + return true; + } + if (!this.fin) { + this.protocolError = true; + this.dropReason = 'Control frames must not be fragmented.'; + return true; + } + } + + if (this.length === 126) { + this.parseState = WAITING_FOR_16_BIT_LENGTH; + } + else if (this.length === 127) { + this.parseState = WAITING_FOR_64_BIT_LENGTH; + } + else { + this.parseState = WAITING_FOR_MASK_KEY; + } + } + } + if (this.parseState === WAITING_FOR_16_BIT_LENGTH) { + if (bufferList.length >= 2) { + bufferList.joinInto(this.frameHeader, 2, 0, 2); + bufferList.advance(2); + this.length = this.frameHeader.readUInt16BE(2, true); + this.parseState = WAITING_FOR_MASK_KEY; + } + } + else if (this.parseState === WAITING_FOR_64_BIT_LENGTH) { + if (bufferList.length >= 8) { + bufferList.joinInto(this.frameHeader, 2, 0, 8); + bufferList.advance(8); + var lengthPair = [ + this.frameHeader.readUInt32BE(2, true), + this.frameHeader.readUInt32BE(2+4, true) + ]; + + if (lengthPair[0] !== 0) { + this.protocolError = true; + this.dropReason = 'Unsupported 64-bit length frame received'; + return true; + } + this.length = lengthPair[1]; + this.parseState = WAITING_FOR_MASK_KEY; + } + } + + if (this.parseState === WAITING_FOR_MASK_KEY) { + if (this.mask) { + if (bufferList.length >= 4) { + bufferList.joinInto(this.maskBytes, 0, 0, 4); + bufferList.advance(4); + this.parseState = WAITING_FOR_PAYLOAD; + } + } + else { + this.parseState = WAITING_FOR_PAYLOAD; + } + } + + if (this.parseState === WAITING_FOR_PAYLOAD) { + if (this.length > this.maxReceivedFrameSize) { + this.frameTooLarge = true; + this.dropReason = 'Frame size of ' + this.length.toString(10) + + ' bytes exceeds maximum accepted frame size'; + return true; + } + + if (this.length === 0) { + this.binaryPayload = new Buffer(0); + this.parseState = COMPLETE; + return true; + } + if (bufferList.length >= this.length) { + this.binaryPayload = bufferList.take(this.length); + bufferList.advance(this.length); + if (this.mask) { + bufferUtil.unmask(this.binaryPayload, this.maskBytes); + // xor(this.binaryPayload, this.maskBytes, 0); + } + + if (this.opcode === 0x08) { // WebSocketOpcode.CONNECTION_CLOSE + if (this.length === 1) { + // Invalid length for a close frame. Must be zero or at least two. + this.binaryPayload = new Buffer(0); + this.invalidCloseFrameLength = true; + } + if (this.length >= 2) { + this.closeStatus = this.binaryPayload.readUInt16BE(0, true); + this.binaryPayload = this.binaryPayload.slice(2); + } + } + + this.parseState = COMPLETE; + return true; + } + } + return false; +}; + +WebSocketFrame.prototype.throwAwayPayload = function(bufferList) { + if (bufferList.length >= this.length) { + bufferList.advance(this.length); + this.parseState = COMPLETE; + return true; + } + return false; +}; + +WebSocketFrame.prototype.toBuffer = function(nullMask) { + var maskKey; + var headerLength = 2; + var data; + var outputPos; + var firstByte = 0x00; + var secondByte = 0x00; + + if (this.fin) { + firstByte |= 0x80; + } + if (this.rsv1) { + firstByte |= 0x40; + } + if (this.rsv2) { + firstByte |= 0x20; + } + if (this.rsv3) { + firstByte |= 0x10; + } + if (this.mask) { + secondByte |= 0x80; + } + + firstByte |= (this.opcode & 0x0F); + + // the close frame is a special case because the close reason is + // prepended to the payload data. + if (this.opcode === 0x08) { + this.length = 2; + if (this.binaryPayload) { + this.length += this.binaryPayload.length; + } + data = new Buffer(this.length); + data.writeUInt16BE(this.closeStatus, 0, true); + if (this.length > 2) { + this.binaryPayload.copy(data, 2); + } + } + else if (this.binaryPayload) { + data = this.binaryPayload; + this.length = data.length; + } + else { + this.length = 0; + } + + if (this.length <= 125) { + // encode the length directly into the two-byte frame header + secondByte |= (this.length & 0x7F); + } + else if (this.length > 125 && this.length <= 0xFFFF) { + // Use 16-bit length + secondByte |= 126; + headerLength += 2; + } + else if (this.length > 0xFFFF) { + // Use 64-bit length + secondByte |= 127; + headerLength += 8; + } + + var output = new Buffer(this.length + headerLength + (this.mask ? 4 : 0)); + + // write the frame header + output[0] = firstByte; + output[1] = secondByte; + + outputPos = 2; + + if (this.length > 125 && this.length <= 0xFFFF) { + // write 16-bit length + output.writeUInt16BE(this.length, outputPos, true); + outputPos += 2; + } + else if (this.length > 0xFFFF) { + // write 64-bit length + output.writeUInt32BE(0x00000000, outputPos, true); + output.writeUInt32BE(this.length, outputPos + 4, true); + outputPos += 8; + } + + if (this.mask) { + maskKey = nullMask ? 0 : (Math.random()*0xFFFFFFFF) | 0; + this.maskBytes.writeUInt32BE(maskKey, 0, true); + + // write the mask key + this.maskBytes.copy(output, outputPos); + outputPos += 4; + + if (data) { + bufferUtil.mask(data, this.maskBytes, output, outputPos, this.length); + } + } + else if (data) { + data.copy(output, outputPos); + } + + return output; +}; + +WebSocketFrame.prototype.toString = function() { + return 'Opcode: ' + this.opcode + ', fin: ' + this.fin + ', length: ' + this.length + ', hasPayload: ' + Boolean(this.binaryPayload) + ', masked: ' + this.mask; +}; + + +module.exports = WebSocketFrame; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRequest.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..f4d96555f9597661244c17265c4e1b144b05cf94 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRequest.js @@ -0,0 +1,524 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var crypto = require('crypto'); +var util = require('util'); +var url = require('url'); +var EventEmitter = require('events').EventEmitter; +var WebSocketConnection = require('./WebSocketConnection'); + +var headerValueSplitRegExp = /,\s*/; +var headerParamSplitRegExp = /;\s*/; +var headerSanitizeRegExp = /[\r\n]/g; +var xForwardedForSeparatorRegExp = /,\s*/; +var separators = [ + '(', ')', '<', '>', '@', + ',', ';', ':', '\\', '\"', + '/', '[', ']', '?', '=', + '{', '}', ' ', String.fromCharCode(9) +]; +var controlChars = [String.fromCharCode(127) /* DEL */]; +for (var i=0; i < 31; i ++) { + /* US-ASCII Control Characters */ + controlChars.push(String.fromCharCode(i)); +} + +var cookieNameValidateRegEx = /([\x00-\x20\x22\x28\x29\x2c\x2f\x3a-\x3f\x40\x5b-\x5e\x7b\x7d\x7f])/; +var cookieValueValidateRegEx = /[^\x21\x23-\x2b\x2d-\x3a\x3c-\x5b\x5d-\x7e]/; +var cookieValueDQuoteValidateRegEx = /^"[^"]*"$/; +var controlCharsAndSemicolonRegEx = /[\x00-\x20\x3b]/g; + +var cookieSeparatorRegEx = /[;,] */; + +var httpStatusDescriptions = { + 100: 'Continue', + 101: 'Switching Protocols', + 200: 'OK', + 201: 'Created', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Found', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary Redirect', + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 406: 'Not Acceptable', + 407: 'Proxy Authorization Required', + 408: 'Request Timeout', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Long', + 414: 'Request-URI Too Long', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 426: 'Upgrade Required', + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Timeout', + 505: 'HTTP Version Not Supported' +}; + +function WebSocketRequest(socket, httpRequest, serverConfig) { + // Superclass Constructor + EventEmitter.call(this); + + this.socket = socket; + this.httpRequest = httpRequest; + this.resource = httpRequest.url; + this.remoteAddress = socket.remoteAddress; + this.remoteAddresses = [this.remoteAddress]; + this.serverConfig = serverConfig; + + // Watch for the underlying TCP socket closing before we call accept + this._socketIsClosing = false; + this._socketCloseHandler = this._handleSocketCloseBeforeAccept.bind(this); + this.socket.on('end', this._socketCloseHandler); + this.socket.on('close', this._socketCloseHandler); + + this._resolved = false; +} + +util.inherits(WebSocketRequest, EventEmitter); + +WebSocketRequest.prototype.readHandshake = function() { + var self = this; + var request = this.httpRequest; + + // Decode URL + this.resourceURL = url.parse(this.resource, true); + + this.host = request.headers['host']; + if (!this.host) { + throw new Error('Client must provide a Host header.'); + } + + this.key = request.headers['sec-websocket-key']; + if (!this.key) { + throw new Error('Client must provide a value for Sec-WebSocket-Key.'); + } + + this.webSocketVersion = parseInt(request.headers['sec-websocket-version'], 10); + + if (!this.webSocketVersion || isNaN(this.webSocketVersion)) { + throw new Error('Client must provide a value for Sec-WebSocket-Version.'); + } + + switch (this.webSocketVersion) { + case 8: + case 13: + break; + default: + var e = new Error('Unsupported websocket client version: ' + this.webSocketVersion + + 'Only versions 8 and 13 are supported.'); + e.httpCode = 426; + e.headers = { + 'Sec-WebSocket-Version': '13' + }; + throw e; + } + + if (this.webSocketVersion === 13) { + this.origin = request.headers['origin']; + } + else if (this.webSocketVersion === 8) { + this.origin = request.headers['sec-websocket-origin']; + } + + // Protocol is optional. + var protocolString = request.headers['sec-websocket-protocol']; + this.protocolFullCaseMap = {}; + this.requestedProtocols = []; + if (protocolString) { + var requestedProtocolsFullCase = protocolString.split(headerValueSplitRegExp); + requestedProtocolsFullCase.forEach(function(protocol) { + var lcProtocol = protocol.toLocaleLowerCase(); + self.requestedProtocols.push(lcProtocol); + self.protocolFullCaseMap[lcProtocol] = protocol; + }); + } + + if (!this.serverConfig.ignoreXForwardedFor && + request.headers['x-forwarded-for']) { + var immediatePeerIP = this.remoteAddress; + this.remoteAddresses = request.headers['x-forwarded-for'] + .split(xForwardedForSeparatorRegExp); + this.remoteAddresses.push(immediatePeerIP); + this.remoteAddress = this.remoteAddresses[0]; + } + + // Extensions are optional. + var extensionsString = request.headers['sec-websocket-extensions']; + this.requestedExtensions = this.parseExtensions(extensionsString); + + // Cookies are optional + var cookieString = request.headers['cookie']; + this.cookies = this.parseCookies(cookieString); +}; + +WebSocketRequest.prototype.parseExtensions = function(extensionsString) { + if (!extensionsString || extensionsString.length === 0) { + return []; + } + var extensions = extensionsString.toLocaleLowerCase().split(headerValueSplitRegExp); + extensions.forEach(function(extension, index, array) { + var params = extension.split(headerParamSplitRegExp); + var extensionName = params[0]; + var extensionParams = params.slice(1); + extensionParams.forEach(function(rawParam, index, array) { + var arr = rawParam.split('='); + var obj = { + name: arr[0], + value: arr[1] + }; + array.splice(index, 1, obj); + }); + var obj = { + name: extensionName, + params: extensionParams + }; + array.splice(index, 1, obj); + }); + return extensions; +}; + +// This function adapted from node-cookie +// https://github.com/shtylman/node-cookie +WebSocketRequest.prototype.parseCookies = function(str) { + // Sanity Check + if (!str || typeof(str) !== 'string') { + return []; + } + + var cookies = []; + var pairs = str.split(cookieSeparatorRegEx); + + pairs.forEach(function(pair) { + var eq_idx = pair.indexOf('='); + if (eq_idx === -1) { + cookies.push({ + name: pair, + value: null + }); + return; + } + + var key = pair.substr(0, eq_idx).trim(); + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' === val[0]) { + val = val.slice(1, -1); + } + + cookies.push({ + name: key, + value: decodeURIComponent(val) + }); + }); + + return cookies; +}; + +WebSocketRequest.prototype.accept = function(acceptedProtocol, allowedOrigin, cookies) { + this._verifyResolution(); + + // TODO: Handle extensions + + var protocolFullCase; + + if (acceptedProtocol) { + protocolFullCase = this.protocolFullCaseMap[acceptedProtocol.toLocaleLowerCase()]; + if (typeof(protocolFullCase) === 'undefined') { + protocolFullCase = acceptedProtocol; + } + } + else { + protocolFullCase = acceptedProtocol; + } + this.protocolFullCaseMap = null; + + // Create key validation hash + var sha1 = crypto.createHash('sha1'); + sha1.update(this.key + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'); + var acceptKey = sha1.digest('base64'); + + var response = 'HTTP/1.1 101 Switching Protocols\r\n' + + 'Upgrade: websocket\r\n' + + 'Connection: Upgrade\r\n' + + 'Sec-WebSocket-Accept: ' + acceptKey + '\r\n'; + + if (protocolFullCase) { + // validate protocol + for (var i=0; i < protocolFullCase.length; i++) { + var charCode = protocolFullCase.charCodeAt(i); + var character = protocolFullCase.charAt(i); + if (charCode < 0x21 || charCode > 0x7E || separators.indexOf(character) !== -1) { + this.reject(500); + throw new Error('Illegal character "' + String.fromCharCode(character) + '" in subprotocol.'); + } + } + if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) { + this.reject(500); + throw new Error('Specified protocol was not requested by the client.'); + } + + protocolFullCase = protocolFullCase.replace(headerSanitizeRegExp, ''); + response += 'Sec-WebSocket-Protocol: ' + protocolFullCase + '\r\n'; + } + this.requestedProtocols = null; + + if (allowedOrigin) { + allowedOrigin = allowedOrigin.replace(headerSanitizeRegExp, ''); + if (this.webSocketVersion === 13) { + response += 'Origin: ' + allowedOrigin + '\r\n'; + } + else if (this.webSocketVersion === 8) { + response += 'Sec-WebSocket-Origin: ' + allowedOrigin + '\r\n'; + } + } + + if (cookies) { + if (!Array.isArray(cookies)) { + this.reject(500); + throw new Error('Value supplied for "cookies" argument must be an array.'); + } + var seenCookies = {}; + cookies.forEach(function(cookie) { + if (!cookie.name || !cookie.value) { + this.reject(500); + throw new Error('Each cookie to set must at least provide a "name" and "value"'); + } + + // Make sure there are no \r\n sequences inserted + cookie.name = cookie.name.replace(controlCharsAndSemicolonRegEx, ''); + cookie.value = cookie.value.replace(controlCharsAndSemicolonRegEx, ''); + + if (seenCookies[cookie.name]) { + this.reject(500); + throw new Error('You may not specify the same cookie name twice.'); + } + seenCookies[cookie.name] = true; + + // token (RFC 2616, Section 2.2) + var invalidChar = cookie.name.match(cookieNameValidateRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie name'); + } + + // RFC 6265, Section 4.1.1 + // *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) | %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + if (cookie.value.match(cookieValueDQuoteValidateRegEx)) { + invalidChar = cookie.value.slice(1, -1).match(cookieValueValidateRegEx); + } else { + invalidChar = cookie.value.match(cookieValueValidateRegEx); + } + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie value'); + } + + var cookieParts = [cookie.name + '=' + cookie.value]; + + // RFC 6265, Section 4.1.1 + // 'Path=' path-value | <any CHAR except CTLs or ';'> + if(cookie.path){ + invalidChar = cookie.path.match(controlCharsAndSemicolonRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie path'); + } + cookieParts.push('Path=' + cookie.path); + } + + // RFC 6265, Section 4.1.2.3 + // 'Domain=' subdomain + if (cookie.domain) { + if (typeof(cookie.domain) !== 'string') { + this.reject(500); + throw new Error('Domain must be specified and must be a string.'); + } + invalidChar = cookie.domain.match(controlCharsAndSemicolonRegEx); + if (invalidChar) { + this.reject(500); + throw new Error('Illegal character ' + invalidChar[0] + ' in cookie domain'); + } + cookieParts.push('Domain=' + cookie.domain.toLowerCase()); + } + + // RFC 6265, Section 4.1.1 + //'Expires=' sane-cookie-date | Force Date object requirement by using only epoch + if (cookie.expires) { + if (!(cookie.expires instanceof Date)){ + this.reject(500); + throw new Error('Value supplied for cookie "expires" must be a vaild date object'); + } + cookieParts.push('Expires=' + cookie.expires.toGMTString()); + } + + // RFC 6265, Section 4.1.1 + //'Max-Age=' non-zero-digit *DIGIT + if (cookie.maxage) { + var maxage = cookie.maxage; + if (typeof(maxage) === 'string') { + maxage = parseInt(maxage, 10); + } + if (isNaN(maxage) || maxage <= 0 ) { + this.reject(500); + throw new Error('Value supplied for cookie "maxage" must be a non-zero number'); + } + maxage = Math.round(maxage); + cookieParts.push('Max-Age=' + maxage.toString(10)); + } + + // RFC 6265, Section 4.1.1 + //'Secure;' + if (cookie.secure) { + if (typeof(cookie.secure) !== 'boolean') { + this.reject(500); + throw new Error('Value supplied for cookie "secure" must be of type boolean'); + } + cookieParts.push('Secure'); + } + + // RFC 6265, Section 4.1.1 + //'HttpOnly;' + if (cookie.httponly) { + if (typeof(cookie.httponly) !== 'boolean') { + this.reject(500); + throw new Error('Value supplied for cookie "httponly" must be of type boolean'); + } + cookieParts.push('HttpOnly'); + } + + response += ('Set-Cookie: ' + cookieParts.join(';') + '\r\n'); + }.bind(this)); + } + + // TODO: handle negotiated extensions + // if (negotiatedExtensions) { + // response += 'Sec-WebSocket-Extensions: ' + negotiatedExtensions.join(', ') + '\r\n'; + // } + + // Mark the request resolved now so that the user can't call accept or + // reject a second time. + this._resolved = true; + this.emit('requestResolved', this); + + response += '\r\n'; + + var connection = new WebSocketConnection(this.socket, [], acceptedProtocol, false, this.serverConfig); + connection.webSocketVersion = this.webSocketVersion; + connection.remoteAddress = this.remoteAddress; + connection.remoteAddresses = this.remoteAddresses; + + var self = this; + + if (this._socketIsClosing) { + // Handle case when the client hangs up before we get a chance to + // accept the connection and send our side of the opening handshake. + cleanupFailedConnection(connection); + } + else { + this.socket.write(response, 'ascii', function(error) { + if (error) { + cleanupFailedConnection(connection); + return; + } + + self._removeSocketCloseListeners(); + connection._addSocketEventListeners(); + }); + } + + this.emit('requestAccepted', connection); + return connection; +}; + +WebSocketRequest.prototype.reject = function(status, reason, extraHeaders) { + this._verifyResolution(); + + // Mark the request resolved now so that the user can't call accept or + // reject a second time. + this._resolved = true; + this.emit('requestResolved', this); + + if (typeof(status) !== 'number') { + status = 403; + } + var response = 'HTTP/1.1 ' + status + ' ' + httpStatusDescriptions[status] + '\r\n' + + 'Connection: close\r\n'; + if (reason) { + reason = reason.replace(headerSanitizeRegExp, ''); + response += 'X-WebSocket-Reject-Reason: ' + reason + '\r\n'; + } + + if (extraHeaders) { + for (var key in extraHeaders) { + var sanitizedValue = extraHeaders[key].toString().replace(headerSanitizeRegExp, ''); + var sanitizedKey = key.replace(headerSanitizeRegExp, ''); + response += (sanitizedKey + ': ' + sanitizedValue + '\r\n'); + } + } + + response += '\r\n'; + this.socket.end(response, 'ascii'); + + this.emit('requestRejected', this); +}; + +WebSocketRequest.prototype._handleSocketCloseBeforeAccept = function() { + this._socketIsClosing = true; + this._removeSocketCloseListeners(); +}; + +WebSocketRequest.prototype._removeSocketCloseListeners = function() { + this.socket.removeListener('end', this._socketCloseHandler); + this.socket.removeListener('close', this._socketCloseHandler); +}; + +WebSocketRequest.prototype._verifyResolution = function() { + if (this._resolved) { + throw new Error('WebSocketRequest may only be accepted or rejected one time.'); + } +}; + +function cleanupFailedConnection(connection) { + // Since we have to return a connection object even if the socket is + // already dead in order not to break the API, we schedule a 'close' + // event on the connection object to occur immediately. + process.nextTick(function() { + // WebSocketConnection.CLOSE_REASON_ABNORMAL = 1006 + // Third param: Skip sending the close frame to a dead socket + connection.drop(1006, 'TCP connection lost before handshake completed.', true); + }); +} + +module.exports = WebSocketRequest; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouter.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouter.js new file mode 100644 index 0000000000000000000000000000000000000000..35bced973e53724530003ef0d393ba70ec299e8d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouter.js @@ -0,0 +1,157 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var extend = require('./utils').extend; +var util = require('util'); +var EventEmitter = require('events').EventEmitter; +var WebSocketRouterRequest = require('./WebSocketRouterRequest'); + +function WebSocketRouter(config) { + // Superclass Constructor + EventEmitter.call(this); + + this.config = { + // The WebSocketServer instance to attach to. + server: null + }; + if (config) { + extend(this.config, config); + } + this.handlers = []; + + this._requestHandler = this.handleRequest.bind(this); + if (this.config.server) { + this.attachServer(this.config.server); + } +} + +util.inherits(WebSocketRouter, EventEmitter); + +WebSocketRouter.prototype.attachServer = function(server) { + if (server) { + this.server = server; + this.server.on('request', this._requestHandler); + } + else { + throw new Error('You must specify a WebSocketServer instance to attach to.'); + } +}; + +WebSocketRouter.prototype.detachServer = function() { + if (this.server) { + this.server.removeListener('request', this._requestHandler); + this.server = null; + } + else { + throw new Error('Cannot detach from server: not attached.'); + } +}; + +WebSocketRouter.prototype.mount = function(path, protocol, callback) { + if (!path) { + throw new Error('You must specify a path for this handler.'); + } + if (!protocol) { + protocol = '____no_protocol____'; + } + if (!callback) { + throw new Error('You must specify a callback for this handler.'); + } + + path = this.pathToRegExp(path); + if (!(path instanceof RegExp)) { + throw new Error('Path must be specified as either a string or a RegExp.'); + } + var pathString = path.toString(); + + // normalize protocol to lower-case + protocol = protocol.toLocaleLowerCase(); + + if (this.findHandlerIndex(pathString, protocol) !== -1) { + throw new Error('You may only mount one handler per path/protocol combination.'); + } + + this.handlers.push({ + 'path': path, + 'pathString': pathString, + 'protocol': protocol, + 'callback': callback + }); +}; +WebSocketRouter.prototype.unmount = function(path, protocol) { + var index = this.findHandlerIndex(this.pathToRegExp(path).toString(), protocol); + if (index !== -1) { + this.handlers.splice(index, 1); + } + else { + throw new Error('Unable to find a route matching the specified path and protocol.'); + } +}; + +WebSocketRouter.prototype.findHandlerIndex = function(pathString, protocol) { + protocol = protocol.toLocaleLowerCase(); + for (var i=0, len=this.handlers.length; i < len; i++) { + var handler = this.handlers[i]; + if (handler.pathString === pathString && handler.protocol === protocol) { + return i; + } + } + return -1; +}; + +WebSocketRouter.prototype.pathToRegExp = function(path) { + if (typeof(path) === 'string') { + if (path === '*') { + path = /^.*$/; + } + else { + path = path.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&'); + path = new RegExp('^' + path + '$'); + } + } + return path; +}; + +WebSocketRouter.prototype.handleRequest = function(request) { + var requestedProtocols = request.requestedProtocols; + if (requestedProtocols.length === 0) { + requestedProtocols = ['____no_protocol____']; + } + + // Find a handler with the first requested protocol first + for (var i=0; i < requestedProtocols.length; i++) { + var requestedProtocol = requestedProtocols[i].toLocaleLowerCase(); + + // find the first handler that can process this request + for (var j=0, len=this.handlers.length; j < len; j++) { + var handler = this.handlers[j]; + if (handler.path.test(request.resourceURL.pathname)) { + if (requestedProtocol === handler.protocol || + handler.protocol === '*') + { + var routerRequest = new WebSocketRouterRequest(request, requestedProtocol); + handler.callback(routerRequest); + return; + } + } + } + } + + // If we get here we were unable to find a suitable handler. + request.reject(404, 'No handler is available for the given request.'); +}; + +module.exports = WebSocketRouter; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js new file mode 100644 index 0000000000000000000000000000000000000000..d3e374574ee9c270870033b3f4a413804e843514 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketRouterRequest.js @@ -0,0 +1,54 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var util = require('util'); +var EventEmitter = require('events').EventEmitter; + +function WebSocketRouterRequest(webSocketRequest, resolvedProtocol) { + // Superclass Constructor + EventEmitter.call(this); + + this.webSocketRequest = webSocketRequest; + if (resolvedProtocol === '____no_protocol____') { + this.protocol = null; + } + else { + this.protocol = resolvedProtocol; + } + this.origin = webSocketRequest.origin; + this.resource = webSocketRequest.resource; + this.resourceURL = webSocketRequest.resourceURL; + this.httpRequest = webSocketRequest.httpRequest; + this.remoteAddress = webSocketRequest.remoteAddress; + this.webSocketVersion = webSocketRequest.webSocketVersion; + this.requestedExtensions = webSocketRequest.requestedExtensions; + this.cookies = webSocketRequest.cookies; +} + +util.inherits(WebSocketRouterRequest, EventEmitter); + +WebSocketRouterRequest.prototype.accept = function(origin, cookies) { + var connection = this.webSocketRequest.accept(this.protocol, origin, cookies); + this.emit('requestAccepted', connection); + return connection; +}; + +WebSocketRouterRequest.prototype.reject = function(status, reason, extraHeaders) { + this.webSocketRequest.reject(status, reason, extraHeaders); + this.emit('requestRejected', this); +}; + +module.exports = WebSocketRouterRequest; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketServer.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketServer.js new file mode 100644 index 0000000000000000000000000000000000000000..c27d967bb26f0fa394cc7374160ccfd95b1d6559 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/WebSocketServer.js @@ -0,0 +1,245 @@ +/************************************************************************ + * Copyright 2010-2015 Brian McKelvey. + * + * 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. + ***********************************************************************/ + +var extend = require('./utils').extend; +var utils = require('./utils'); +var util = require('util'); +var debug = require('debug')('websocket:server'); +var EventEmitter = require('events').EventEmitter; +var WebSocketRequest = require('./WebSocketRequest'); + +var WebSocketServer = function WebSocketServer(config) { + // Superclass Constructor + EventEmitter.call(this); + + this._handlers = { + upgrade: this.handleUpgrade.bind(this), + requestAccepted: this.handleRequestAccepted.bind(this), + requestResolved: this.handleRequestResolved.bind(this) + }; + this.connections = []; + this.pendingRequests = []; + if (config) { + this.mount(config); + } +}; + +util.inherits(WebSocketServer, EventEmitter); + +WebSocketServer.prototype.mount = function(config) { + this.config = { + // The http server instance to attach to. Required. + httpServer: null, + + // 64KiB max frame size. + maxReceivedFrameSize: 0x10000, + + // 1MiB max message size, only applicable if + // assembleFragments is true + maxReceivedMessageSize: 0x100000, + + // Outgoing messages larger than fragmentationThreshold will be + // split into multiple fragments. + fragmentOutgoingMessages: true, + + // Outgoing frames are fragmented if they exceed this threshold. + // Default is 16KiB + fragmentationThreshold: 0x4000, + + // If true, the server will automatically send a ping to all + // clients every 'keepaliveInterval' milliseconds. The timer is + // reset on any received data from the client. + keepalive: true, + + // The interval to send keepalive pings to connected clients if the + // connection is idle. Any received data will reset the counter. + keepaliveInterval: 20000, + + // If true, the server will consider any connection that has not + // received any data within the amount of time specified by + // 'keepaliveGracePeriod' after a keepalive ping has been sent to + // be dead, and will drop the connection. + // Ignored if keepalive is false. + dropConnectionOnKeepaliveTimeout: true, + + // The amount of time to wait after sending a keepalive ping before + // closing the connection if the connected peer does not respond. + // Ignored if keepalive is false. + keepaliveGracePeriod: 10000, + + // Whether to use native TCP keep-alive instead of WebSockets ping + // and pong packets. Native TCP keep-alive sends smaller packets + // on the wire and so uses bandwidth more efficiently. This may + // be more important when talking to mobile devices. + // If this value is set to true, then these values will be ignored: + // keepaliveGracePeriod + // dropConnectionOnKeepaliveTimeout + useNativeKeepalive: false, + + // If true, fragmented messages will be automatically assembled + // and the full message will be emitted via a 'message' event. + // If false, each frame will be emitted via a 'frame' event and + // the application will be responsible for aggregating multiple + // fragmented frames. Single-frame messages will emit a 'message' + // event in addition to the 'frame' event. + // Most users will want to leave this set to 'true' + assembleFragments: true, + + // If this is true, websocket connections will be accepted + // regardless of the path and protocol specified by the client. + // The protocol accepted will be the first that was requested + // by the client. Clients from any origin will be accepted. + // This should only be used in the simplest of cases. You should + // probably leave this set to 'false' and inspect the request + // object to make sure it's acceptable before accepting it. + autoAcceptConnections: false, + + // Whether or not the X-Forwarded-For header should be respected. + // It's important to set this to 'true' when accepting connections + // from untrusted clients, as a malicious client could spoof its + // IP address by simply setting this header. It's meant to be added + // by a trusted proxy or other intermediary within your own + // infrastructure. + // See: http://en.wikipedia.org/wiki/X-Forwarded-For + ignoreXForwardedFor: false, + + // The Nagle Algorithm makes more efficient use of network resources + // by introducing a small delay before sending small packets so that + // multiple messages can be batched together before going onto the + // wire. This however comes at the cost of latency, so the default + // is to disable it. If you don't need low latency and are streaming + // lots of small messages, you can change this to 'false' + disableNagleAlgorithm: true, + + // The number of milliseconds to wait after sending a close frame + // for an acknowledgement to come back before giving up and just + // closing the socket. + closeTimeout: 5000 + }; + extend(this.config, config); + + if (this.config.httpServer) { + if (!Array.isArray(this.config.httpServer)) { + this.config.httpServer = [this.config.httpServer]; + } + var upgradeHandler = this._handlers.upgrade; + this.config.httpServer.forEach(function(httpServer) { + httpServer.on('upgrade', upgradeHandler); + }); + } + else { + throw new Error('You must specify an httpServer on which to mount the WebSocket server.'); + } +}; + +WebSocketServer.prototype.unmount = function() { + var upgradeHandler = this._handlers.upgrade; + this.config.httpServer.forEach(function(httpServer) { + httpServer.removeListener('upgrade', upgradeHandler); + }); +}; + +WebSocketServer.prototype.closeAllConnections = function() { + this.connections.forEach(function(connection) { + connection.close(); + }); + this.pendingRequests.forEach(function(request) { + process.nextTick(function() { + request.reject(503); // HTTP 503 Service Unavailable + }); + }); +}; + +WebSocketServer.prototype.broadcast = function(data) { + if (Buffer.isBuffer(data)) { + this.broadcastBytes(data); + } + else if (typeof(data.toString) === 'function') { + this.broadcastUTF(data); + } +}; + +WebSocketServer.prototype.broadcastUTF = function(utfData) { + this.connections.forEach(function(connection) { + connection.sendUTF(utfData); + }); +}; + +WebSocketServer.prototype.broadcastBytes = function(binaryData) { + this.connections.forEach(function(connection) { + connection.sendBytes(binaryData); + }); +}; + +WebSocketServer.prototype.shutDown = function() { + this.unmount(); + this.closeAllConnections(); +}; + +WebSocketServer.prototype.handleUpgrade = function(request, socket) { + var wsRequest = new WebSocketRequest(socket, request, this.config); + try { + wsRequest.readHandshake(); + } + catch(e) { + wsRequest.reject( + e.httpCode ? e.httpCode : 400, + e.message, + e.headers + ); + debug('Invalid handshake: %s', e.message); + return; + } + + this.pendingRequests.push(wsRequest); + + wsRequest.once('requestAccepted', this._handlers.requestAccepted); + wsRequest.once('requestResolved', this._handlers.requestResolved); + + if (!this.config.autoAcceptConnections && utils.eventEmitterListenerCount(this, 'request') > 0) { + this.emit('request', wsRequest); + } + else if (this.config.autoAcceptConnections) { + wsRequest.accept(wsRequest.requestedProtocols[0], wsRequest.origin); + } + else { + wsRequest.reject(404, 'No handler is configured to accept the connection.'); + } +}; + +WebSocketServer.prototype.handleRequestAccepted = function(connection) { + var self = this; + connection.once('close', function(closeReason, description) { + self.handleConnectionClose(connection, closeReason, description); + }); + this.connections.push(connection); + this.emit('connect', connection); +}; + +WebSocketServer.prototype.handleConnectionClose = function(connection, closeReason, description) { + var index = this.connections.indexOf(connection); + if (index !== -1) { + this.connections.splice(index, 1); + } + this.emit('close', connection, closeReason, description); +}; + +WebSocketServer.prototype.handleRequestResolved = function(request) { + var index = this.pendingRequests.indexOf(request); + if (index !== -1) { this.pendingRequests.splice(index, 1); } +}; + +module.exports = WebSocketServer; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/browser.js new file mode 100644 index 0000000000000000000000000000000000000000..c11cea9dd96b1e1fa2e8b2a49fd53cc5796454f1 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/browser.js @@ -0,0 +1,42 @@ +var _global = (function() { return this; })(); +var NativeWebSocket = _global.WebSocket || _global.MozWebSocket; +var websocket_version = require('./version'); + + +/** + * Expose a W3C WebSocket class with just one or two arguments. + */ +function W3CWebSocket(uri, protocols) { + var native_instance; + + if (protocols) { + native_instance = new NativeWebSocket(uri, protocols); + } + else { + native_instance = new NativeWebSocket(uri); + } + + /** + * 'native_instance' is an instance of nativeWebSocket (the browser's WebSocket + * class). Since it is an Object it will be returned as it is when creating an + * instance of W3CWebSocket via 'new W3CWebSocket()'. + * + * ECMAScript 5: http://bclary.com/2004/11/07/#a-13.2.2 + */ + return native_instance; +} +if (NativeWebSocket) { + ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED'].forEach(function(prop) { + Object.defineProperty(W3CWebSocket, prop, { + get: function() { return NativeWebSocket[prop]; } + }); + }); +} + +/** + * Module exports. + */ +module.exports = { + 'w3cwebsocket' : NativeWebSocket ? W3CWebSocket : null, + 'version' : websocket_version +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/utils.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..6506dc9744007fa5d8bc4c89ba81c1f04a509aef --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/utils.js @@ -0,0 +1,60 @@ +var noop = exports.noop = function(){}; + +exports.extend = function extend(dest, source) { + for (var prop in source) { + dest[prop] = source[prop]; + } +}; + +exports.eventEmitterListenerCount = + require('events').EventEmitter.listenerCount || + function(emitter, type) { return emitter.listeners(type).length; }; + + + + + +exports.BufferingLogger = function createBufferingLogger(identifier, uniqueID) { + var logFunction = require('debug')(identifier); + if (logFunction.enabled) { + var logger = new BufferingLogger(identifier, uniqueID, logFunction); + var debug = logger.log.bind(logger); + debug.printOutput = logger.printOutput.bind(logger); + debug.enabled = logFunction.enabled; + return debug; + } + logFunction.printOutput = noop; + return logFunction; +}; + +function BufferingLogger(identifier, uniqueID, logFunction) { + this.logFunction = logFunction; + this.identifier = identifier; + this.uniqueID = uniqueID; + this.buffer = []; +} + +BufferingLogger.prototype.log = function() { + this.buffer.push([ new Date(), Array.prototype.slice.call(arguments) ]); + return this; +}; + +BufferingLogger.prototype.clear = function() { + this.buffer = []; + return this; +}; + +BufferingLogger.prototype.printOutput = function(logFunction) { + if (!logFunction) { logFunction = this.logFunction; } + var uniqueID = this.uniqueID; + this.buffer.forEach(function(entry) { + var date = entry[0].toLocaleString(); + var args = entry[1].slice(); + var formatString = args[0]; + if (formatString !== (void 0) && formatString !== null) { + formatString = '%s - %s - ' + formatString.toString(); + args.splice(0, 1, formatString, date, uniqueID); + logFunction.apply(global, args); + } + }); +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/version.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/version.js new file mode 100644 index 0000000000000000000000000000000000000000..81f6e78b6196ee3d29466c59eb870981ba6e2986 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/version.js @@ -0,0 +1 @@ +module.exports = require('../package.json').version; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/websocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..6242d561d916cd502884463f2760fbfada533248 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/lib/websocket.js @@ -0,0 +1,11 @@ +module.exports = { + 'server' : require('./WebSocketServer'), + 'client' : require('./WebSocketClient'), + 'router' : require('./WebSocketRouter'), + 'frame' : require('./WebSocketFrame'), + 'request' : require('./WebSocketRequest'), + 'connection' : require('./WebSocketConnection'), + 'w3cwebsocket' : require('./W3CWebSocket'), + 'deprecation' : require('./Deprecation'), + 'version' : require('./version') +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/package.json new file mode 100644 index 0000000000000000000000000000000000000000..d805f8dd9b99251128a44de30c622b3acc97e96f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/package.json @@ -0,0 +1,95 @@ +{ + "_from": "websocket", + "_id": "websocket@1.0.25", + "_inBundle": false, + "_integrity": "sha512-M58njvi6ZxVb5k7kpnHh2BvNKuBWiwIYvsToErBzWhvBZYwlEiLcyLrG41T1jRcrY9ettqPYEqduLI7ul54CVQ==", + "_location": "/websocket", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "websocket", + "name": "websocket", + "escapedName": "websocket", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.25.tgz", + "_shasum": "998ec790f0a3eacb8b08b50a4350026692a11958", + "_spec": "websocket", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts", + "author": { + "name": "Brian McKelvey", + "email": "brian@worlize.com", + "url": "https://www.worlize.com/" + }, + "browser": "lib/browser.js", + "bugs": { + "url": "https://github.com/theturtle32/WebSocket-Node/issues" + }, + "bundleDependencies": false, + "config": { + "verbose": false + }, + "contributors": [ + { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net", + "url": "http://dev.sipdoc.net" + } + ], + "dependencies": { + "debug": "^2.2.0", + "nan": "^2.3.3", + "typedarray-to-buffer": "^3.1.2", + "yaeti": "^0.0.6" + }, + "deprecated": false, + "description": "Websocket Client & Server Library implementing the WebSocket protocol as specified in RFC 6455.", + "devDependencies": { + "buffer-equal": "^1.0.0", + "faucet": "^0.0.1", + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jshint": "^2.0.4", + "jshint": "^2.0.0", + "jshint-stylish": "^2.2.1", + "tape": "^4.0.1" + }, + "directories": { + "lib": "./lib" + }, + "engines": { + "node": ">=0.10.0" + }, + "homepage": "https://github.com/theturtle32/WebSocket-Node", + "keywords": [ + "websocket", + "websockets", + "socket", + "networking", + "comet", + "push", + "RFC-6455", + "realtime", + "server", + "client" + ], + "license": "Apache-2.0", + "main": "index", + "name": "websocket", + "repository": { + "type": "git", + "url": "git+https://github.com/theturtle32/WebSocket-Node.git" + }, + "scripts": { + "gulp": "gulp", + "install": "(node-gyp rebuild 2> builderror.log) || (exit 0)", + "test": "faucet test/unit" + }, + "version": "1.0.25" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/bufferutil.cc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/bufferutil.cc new file mode 100644 index 0000000000000000000000000000000000000000..d2f8d2d61f29ebf8a712d1b5f1142fa121f63f92 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/bufferutil.cc @@ -0,0 +1,121 @@ +/*! + * BufferUtil originally from: + * ws: a node.js websocket client + * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +#include <v8.h> +#include <node.h> +#include <node_version.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <stdlib.h> +#include <string.h> +#include <wchar.h> +#include <stdio.h> +#include "nan.h" + +using namespace v8; +using namespace node; + +class BufferUtil : public ObjectWrap +{ +public: + + static void Initialize(v8::Handle<v8::Object> target) + { + Nan::HandleScope scope; + Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + Nan::SetMethod(t, "unmask", BufferUtil::Unmask); + Nan::SetMethod(t, "mask", BufferUtil::Mask); + Nan::SetMethod(t, "merge", BufferUtil::Merge); + Nan::Set(target, Nan::New<String>("BufferUtil").ToLocalChecked(), t->GetFunction()); + } + +protected: + + static NAN_METHOD(New) + { + Nan::HandleScope scope; + BufferUtil* bufferUtil = new BufferUtil(); + bufferUtil->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } + + static NAN_METHOD(Merge) + { + Nan::HandleScope scope; + Local<Object> bufferObj = info[0]->ToObject(); + char* buffer = Buffer::Data(bufferObj); + Local<Array> array = Local<Array>::Cast(info[1]); + unsigned int arrayLength = array->Length(); + size_t offset = 0; + unsigned int i; + for (i = 0; i < arrayLength; ++i) { + Local<Object> src = array->Get(i)->ToObject(); + size_t length = Buffer::Length(src); + memcpy(buffer + offset, Buffer::Data(src), length); + offset += length; + } + info.GetReturnValue().Set(Nan::True()); + } + + static NAN_METHOD(Unmask) + { + Nan::HandleScope scope; + Local<Object> buffer_obj = info[0]->ToObject(); + size_t length = Buffer::Length(buffer_obj); + Local<Object> mask_obj = info[1]->ToObject(); + unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); + unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); + size_t len32 = length / 4; + unsigned int i; + for (i = 0; i < len32; ++i) *(from + i) ^= *mask; + from += i; + switch (length % 4) { + case 3: *((unsigned char*)from+2) = *((unsigned char*)from+2) ^ ((unsigned char*)mask)[2]; + case 2: *((unsigned char*)from+1) = *((unsigned char*)from+1) ^ ((unsigned char*)mask)[1]; + case 1: *((unsigned char*)from ) = *((unsigned char*)from ) ^ ((unsigned char*)mask)[0]; + case 0:; + } + info.GetReturnValue().Set(Nan::True()); + } + + static NAN_METHOD(Mask) + { + Nan::HandleScope scope; + Local<Object> buffer_obj = info[0]->ToObject(); + Local<Object> mask_obj = info[1]->ToObject(); + unsigned int *mask = (unsigned int*)Buffer::Data(mask_obj); + Local<Object> output_obj = info[2]->ToObject(); + unsigned int dataOffset = info[3]->Int32Value(); + unsigned int length = info[4]->Int32Value(); + unsigned int* to = (unsigned int*)(Buffer::Data(output_obj) + dataOffset); + unsigned int* from = (unsigned int*)Buffer::Data(buffer_obj); + unsigned int len32 = length / 4; + unsigned int i; + for (i = 0; i < len32; ++i) *(to + i) = *(from + i) ^ *mask; + to += i; + from += i; + switch (length % 4) { + case 3: *((unsigned char*)to+2) = *((unsigned char*)from+2) ^ *((unsigned char*)mask+2); + case 2: *((unsigned char*)to+1) = *((unsigned char*)from+1) ^ *((unsigned char*)mask+1); + case 1: *((unsigned char*)to ) = *((unsigned char*)from ) ^ *((unsigned char*)mask); + case 0:; + } + info.GetReturnValue().Set(Nan::True()); + } +}; + +#if !NODE_VERSION_AT_LEAST(0,10,0) +extern "C" +#endif +void init (Handle<Object> target) +{ + Nan::HandleScope scope; + BufferUtil::Initialize(target); +} + +NODE_MODULE(bufferutil, init) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/validation.cc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/validation.cc new file mode 100644 index 0000000000000000000000000000000000000000..8e2347e54e79643b4cf1a2aa2b5c15b21d1489af --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/src/validation.cc @@ -0,0 +1,148 @@ +/*! + * UTF-8 Validation Code originally from: + * ws: a node.js websocket client + * Copyright(c) 2015 Einar Otto Stangvik <einaros@gmail.com> + * MIT Licensed + */ + +#include <v8.h> +#include <node.h> +#include <node_version.h> +#include <node_buffer.h> +#include <node_object_wrap.h> +#include <stdlib.h> +#include <wchar.h> +#include <stdio.h> +#include "nan.h" + +using namespace v8; +using namespace node; + +#define UNI_SUR_HIGH_START (uint32_t) 0xD800 +#define UNI_SUR_LOW_END (uint32_t) 0xDFFF +#define UNI_REPLACEMENT_CHAR (uint32_t) 0x0000FFFD +#define UNI_MAX_LEGAL_UTF32 (uint32_t) 0x0010FFFF + +static const uint8_t trailingBytesForUTF8[256] = { + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, + 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, + 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5 +}; + +static const uint32_t offsetsFromUTF8[6] = { + 0x00000000, 0x00003080, 0x000E2080, + 0x03C82080, 0xFA082080, 0x82082080 +}; + +static int isLegalUTF8(const uint8_t *source, const int length) +{ + uint8_t a; + const uint8_t *srcptr = source+length; + switch (length) { + default: return 0; + /* Everything else falls through when "true"... */ + /* RFC3629 makes 5 & 6 bytes UTF-8 illegal + case 6: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 5: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; */ + case 4: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 3: if ((a = (*--srcptr)) < 0x80 || a > 0xBF) return 0; + case 2: if ((a = (*--srcptr)) > 0xBF) return 0; + switch (*source) { + /* no fall-through in this inner switch */ + case 0xE0: if (a < 0xA0) return 0; break; + case 0xED: if (a > 0x9F) return 0; break; + case 0xF0: if (a < 0x90) return 0; break; + case 0xF4: if (a > 0x8F) return 0; break; + default: if (a < 0x80) return 0; + } + + case 1: if (*source >= 0x80 && *source < 0xC2) return 0; + } + if (*source > 0xF4) return 0; + return 1; +} + +int is_valid_utf8 (size_t len, char *value) +{ + /* is the string valid UTF-8? */ + for (unsigned int i = 0; i < len; i++) { + uint32_t ch = 0; + uint8_t extrabytes = trailingBytesForUTF8[(uint8_t) value[i]]; + + if (extrabytes + i >= len) + return 0; + + if (isLegalUTF8 ((uint8_t *) (value + i), extrabytes + 1) == 0) return 0; + + switch (extrabytes) { + case 5 : ch += (uint8_t) value[i++]; ch <<= 6; + case 4 : ch += (uint8_t) value[i++]; ch <<= 6; + case 3 : ch += (uint8_t) value[i++]; ch <<= 6; + case 2 : ch += (uint8_t) value[i++]; ch <<= 6; + case 1 : ch += (uint8_t) value[i++]; ch <<= 6; + case 0 : ch += (uint8_t) value[i]; + } + + ch -= offsetsFromUTF8[extrabytes]; + + if (ch <= UNI_MAX_LEGAL_UTF32) { + if (ch >= UNI_SUR_HIGH_START && ch <= UNI_SUR_LOW_END) + return 0; + } else { + return 0; + } + } + + return 1; +} + +class Validation : public ObjectWrap +{ +public: + + static void Initialize(v8::Handle<v8::Object> target) + { + Nan::HandleScope scope; + Local<FunctionTemplate> t = Nan::New<FunctionTemplate>(New); + t->InstanceTemplate()->SetInternalFieldCount(1); + Nan::SetMethod(t, "isValidUTF8", Validation::IsValidUTF8); + Nan::Set(target, Nan::New<String>("Validation").ToLocalChecked(), t->GetFunction()); + } + +protected: + + static NAN_METHOD(New) + { + Nan::HandleScope scope; + Validation* validation = new Validation(); + validation->Wrap(info.This()); + info.GetReturnValue().Set(info.This()); + } + + static NAN_METHOD(IsValidUTF8) + { + Nan::HandleScope scope; + if (!Buffer::HasInstance(info[0])) { + return Nan::ThrowTypeError("First argument needs to be a buffer"); + } + Local<Object> buffer_obj = info[0]->ToObject(); + char *buffer_data = Buffer::Data(buffer_obj); + size_t buffer_length = Buffer::Length(buffer_obj); + info.GetReturnValue().Set(is_valid_utf8(buffer_length, buffer_data) == 1 ? Nan::True() : Nan::False()); + } +}; +#if !NODE_VERSION_AT_LEAST(0,10,0) +extern "C" +#endif +void init (Handle<Object> target) +{ + Nan::HandleScope scope; + Validation::Initialize(target); +} + +NODE_MODULE(validation, init) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/vendor/FastBufferList.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/vendor/FastBufferList.js new file mode 100644 index 0000000000000000000000000000000000000000..aabf096a7cc18ba6ed4635a0068cc918645fc1e0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/websocket/vendor/FastBufferList.js @@ -0,0 +1,193 @@ +// This file was copied from https://github.com/substack/node-bufferlist +// and modified to be able to copy bytes from the bufferlist directly into +// a pre-existing fixed-size buffer without an additional memory allocation. + +// bufferlist.js +// Treat a linked list of buffers as a single variable-size buffer. +var Buffer = require('buffer').Buffer; +var EventEmitter = require('events').EventEmitter; + +module.exports = BufferList; +module.exports.BufferList = BufferList; // backwards compatibility + +function BufferList(opts) { + if (!(this instanceof BufferList)) return new BufferList(opts); + EventEmitter.call(this); + var self = this; + + if (typeof(opts) == 'undefined') opts = {}; + + // default encoding to use for take(). Leaving as 'undefined' + // makes take() return a Buffer instead. + self.encoding = opts.encoding; + + // constructor to use for Buffer-esque operations + self.construct = opts.construct || Buffer; + + var head = { next : null, buffer : null }; + var last = { next : null, buffer : null }; + + // length can get negative when advanced past the end + // and this is the desired behavior + var length = 0; + self.__defineGetter__('length', function () { + return length; + }); + + // keep an offset of the head to decide when to head = head.next + var offset = 0; + + // Write to the bufferlist. Emits 'write'. Always returns true. + self.write = function (buf) { + if (!head.buffer) { + head.buffer = buf; + last = head; + } + else { + last.next = { next : null, buffer : buf }; + last = last.next; + } + length += buf.length; + self.emit('write', buf); + return true; + }; + + self.end = function (buf) { + if (Buffer.isBuffer(buf)) self.write(buf); + }; + + // Push buffers to the end of the linked list. (deprecated) + // Return this (self). + self.push = function () { + var args = [].concat.apply([], arguments); + args.forEach(self.write); + return self; + }; + + // For each buffer, perform some action. + // If fn's result is a true value, cut out early. + // Returns this (self). + self.forEach = function (fn) { + if (!head.buffer) return new self.construct(0); + + if (head.buffer.length - offset <= 0) return self; + var firstBuf = head.buffer.slice(offset); + + var b = { buffer : firstBuf, next : head.next }; + + while (b && b.buffer) { + var r = fn(b.buffer); + if (r) break; + b = b.next; + } + + return self; + }; + + // Create a single Buffer out of all the chunks or some subset specified by + // start and one-past the end (like slice) in bytes. + self.join = function (start, end) { + if (!head.buffer) return new self.construct(0); + if (start == undefined) start = 0; + if (end == undefined) end = self.length; + + var big = new self.construct(end - start); + var ix = 0; + self.forEach(function (buffer) { + if (start < (ix + buffer.length) && ix < end) { + // at least partially contained in the range + buffer.copy( + big, + Math.max(0, ix - start), + Math.max(0, start - ix), + Math.min(buffer.length, end - ix) + ); + } + ix += buffer.length; + if (ix > end) return true; // stop processing past end + }); + + return big; + }; + + self.joinInto = function (targetBuffer, targetStart, sourceStart, sourceEnd) { + if (!head.buffer) return new self.construct(0); + if (sourceStart == undefined) sourceStart = 0; + if (sourceEnd == undefined) sourceEnd = self.length; + + var big = targetBuffer; + if (big.length - targetStart < sourceEnd - sourceStart) { + throw new Error("Insufficient space available in target Buffer."); + } + var ix = 0; + self.forEach(function (buffer) { + if (sourceStart < (ix + buffer.length) && ix < sourceEnd) { + // at least partially contained in the range + buffer.copy( + big, + Math.max(targetStart, targetStart + ix - sourceStart), + Math.max(0, sourceStart - ix), + Math.min(buffer.length, sourceEnd - ix) + ); + } + ix += buffer.length; + if (ix > sourceEnd) return true; // stop processing past end + }); + + return big; + }; + + // Advance the buffer stream by n bytes. + // If n the aggregate advance offset passes the end of the buffer list, + // operations such as .take() will return empty strings until enough data is + // pushed. + // Returns this (self). + self.advance = function (n) { + offset += n; + length -= n; + while (head.buffer && offset >= head.buffer.length) { + offset -= head.buffer.length; + head = head.next + ? head.next + : { buffer : null, next : null } + ; + } + if (head.buffer === null) last = { next : null, buffer : null }; + self.emit('advance', n); + return self; + }; + + // Take n bytes from the start of the buffers. + // Returns a string. + // If there are less than n bytes in all the buffers or n is undefined, + // returns the entire concatenated buffer string. + self.take = function (n, encoding) { + if (n == undefined) n = self.length; + else if (typeof n !== 'number') { + encoding = n; + n = self.length; + } + var b = head; + if (!encoding) encoding = self.encoding; + if (encoding) { + var acc = ''; + self.forEach(function (buffer) { + if (n <= 0) return true; + acc += buffer.toString( + encoding, 0, Math.min(n,buffer.length) + ); + n -= buffer.length; + }); + return acc; + } else { + // If no 'encoding' is specified, then return a Buffer. + return self.join(0, n); + } + }; + + // The entire concatenated buffer as a string. + self.toString = function () { + return self.take('binary'); + }; +} +require('util').inherits(BufferList, EventEmitter); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a145cd1dff053182c444072e1c199926e0cb09ad --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2011 Einar Otto Stangvik <einaros@gmail.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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/README.md new file mode 100644 index 0000000000000000000000000000000000000000..8f94ca303c5f55dfa355991991b794f9cdf7c1f4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/README.md @@ -0,0 +1,389 @@ +# ws: a Node.js WebSocket library + +[](https://www.npmjs.com/package/ws) +[](https://travis-ci.org/websockets/ws) +[](https://ci.appveyor.com/project/lpinca/ws) +[](https://coveralls.io/r/websockets/ws?branch=master) + +ws is a simple to use, blazing fast, and thoroughly tested WebSocket client +and server implementation. + +Passes the quite extensive Autobahn test suite: [server][server-report], +[client][client-report]. + +**Note**: This module does not work in the browser. The client in the docs is a +reference to a back end with the role of a client in the WebSocket +communication. Browser clients must use the native +[`WebSocket`](https://developer.mozilla.org/en-US/docs/Web/API/WebSocket) object. +To make the same code work seamlessly on Node.js and the browser, you can use +one of the many wrappers available on npm, like +[isomorphic-ws](https://github.com/heineiuo/isomorphic-ws). + +## Table of Contents + +* [Protocol support](#protocol-support) +* [Installing](#installing) + + [Opt-in for performance and spec compliance](#opt-in-for-performance-and-spec-compliance) +* [API docs](#api-docs) +* [WebSocket compression](#websocket-compression) +* [Usage examples](#usage-examples) + + [Sending and receiving text data](#sending-and-receiving-text-data) + + [Sending binary data](#sending-binary-data) + + [Server example](#server-example) + + [Broadcast example](#broadcast-example) + + [ExpressJS example](#expressjs-example) + + [echo.websocket.org demo](#echowebsocketorg-demo) + + [Other examples](#other-examples) +* [Error handling best practices](#error-handling-best-practices) +* [FAQ](#faq) + + [How to get the IP address of the client?](#how-to-get-the-ip-address-of-the-client) + + [How to detect and close broken connections?](#how-to-detect-and-close-broken-connections) + + [How to connect via a proxy?](#how-to-connect-via-a-proxy) +* [Changelog](#changelog) +* [License](#license) + +## Protocol support + +* **HyBi drafts 07-12** (Use the option `protocolVersion: 8`) +* **HyBi drafts 13-17** (Current default, alternatively option `protocolVersion: 13`) + +## Installing + +``` +npm install --save ws +``` + +### Opt-in for performance and spec compliance + +There are 2 optional modules that can be installed along side with the ws +module. These modules are binary addons which improve certain operations. +Prebuilt binaries are available for the most popular platforms so you don't +necessarily need to have a C++ compiler installed on your machine. + +- `npm install --save-optional bufferutil`: Allows to efficiently perform + operations such as masking and unmasking the data payload of the WebSocket + frames. +- `npm install --save-optional utf-8-validate`: Allows to efficiently check + if a message contains valid UTF-8 as required by the spec. + +## API docs + +See [`/doc/ws.md`](./doc/ws.md) for Node.js-like docs for the ws classes. + +## WebSocket compression + +ws supports the [permessage-deflate extension][permessage-deflate] which +enables the client and server to negotiate a compression algorithm and its +parameters, and then selectively apply it to the data payloads of each +WebSocket message. + +The extension is disabled by default on the server and enabled by default on +the client. It adds a significant overhead in terms of performance and memory +consumption so we suggest to enable it only if it is really needed. + +Note that Node.js has a variety of issues with high-performance compression, +where increased concurrency, especially on Linux, can lead to +[catastrophic memory fragmentation][node-zlib-bug] and slow performance. +If you intend to use permessage-deflate in production, it is worthwhile to set +up a test representative of your workload and ensure Node.js/zlib will handle +it with acceptable performance and memory usage. + +Tuning of permessage-deflate can be done via the options defined below. You can +also use `zlibDeflateOptions` and `zlibInflateOptions`, which is passed directly +into the creation of [raw deflate/inflate streams][node-zlib-deflaterawdocs]. + +See [the docs][ws-server-options] for more options. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ + port: 8080, + perMessageDeflate: { + zlibDeflateOptions: { // See zlib defaults. + chunkSize: 1024, + memLevel: 7, + level: 3, + }, + zlibInflateOptions: { + chunkSize: 10 * 1024 + }, + // Other options settable: + clientNoContextTakeover: true, // Defaults to negotiated value. + serverNoContextTakeover: true, // Defaults to negotiated value. + clientMaxWindowBits: 10, // Defaults to negotiated value. + serverMaxWindowBits: 10, // Defaults to negotiated value. + // Below options specified as default values. + concurrencyLimit: 10, // Limits zlib concurrency for perf. + threshold: 1024, // Size (in bytes) below which messages + // should not be compressed. + } +}); +``` + +The client will only use the extension if it is supported and enabled on the +server. To always disable the extension on the client set the +`perMessageDeflate` option to `false`. + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path', { + perMessageDeflate: false +}); +``` + +## Usage examples + +### Sending and receiving text data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + ws.send('something'); +}); + +ws.on('message', function incoming(data) { + console.log(data); +}); +``` + +### Sending binary data + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('ws://www.host.com/path'); + +ws.on('open', function open() { + const array = new Float32Array(5); + + for (var i = 0; i < array.length; ++i) { + array[i] = i / 2; + } + + ws.send(array); +}); +``` + +### Server example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); +``` + +### Broadcast example + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +// Broadcast to all. +wss.broadcast = function broadcast(data) { + wss.clients.forEach(function each(client) { + if (client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); +}; + +wss.on('connection', function connection(ws) { + ws.on('message', function incoming(data) { + // Broadcast to everyone else. + wss.clients.forEach(function each(client) { + if (client !== ws && client.readyState === WebSocket.OPEN) { + client.send(data); + } + }); + }); +}); +``` + +### ExpressJS example + +```js +const express = require('express'); +const http = require('http'); +const url = require('url'); +const WebSocket = require('ws'); + +const app = express(); + +app.use(function (req, res) { + res.send({ msg: "hello" }); +}); + +const server = http.createServer(app); +const wss = new WebSocket.Server({ server }); + +wss.on('connection', function connection(ws, req) { + const location = url.parse(req.url, true); + // You might use location.query.access_token to authenticate or share sessions + // or req.headers.cookie (see http://stackoverflow.com/a/16395220/151312) + + ws.on('message', function incoming(message) { + console.log('received: %s', message); + }); + + ws.send('something'); +}); + +server.listen(8080, function listening() { + console.log('Listening on %d', server.address().port); +}); +``` + +### echo.websocket.org demo + +```js +const WebSocket = require('ws'); + +const ws = new WebSocket('wss://echo.websocket.org/', { + origin: 'https://websocket.org' +}); + +ws.on('open', function open() { + console.log('connected'); + ws.send(Date.now()); +}); + +ws.on('close', function close() { + console.log('disconnected'); +}); + +ws.on('message', function incoming(data) { + console.log(`Roundtrip time: ${Date.now() - data} ms`); + + setTimeout(function timeout() { + ws.send(Date.now()); + }, 500); +}); +``` + +### Other examples + +For a full example with a browser client communicating with a ws server, see the +examples folder. + +Otherwise, see the test cases. + +## Error handling best practices + +```js +// If the WebSocket is closed before the following send is attempted +ws.send('something'); + +// Errors (both immediate and async write errors) can be detected in an optional +// callback. The callback is also the only way of being notified that data has +// actually been sent. +ws.send('something', function ack(error) { + // If error is not defined, the send has been completed, otherwise the error + // object will indicate what failed. +}); + +// Immediate errors can also be handled with `try...catch`, but **note** that +// since sends are inherently asynchronous, socket write failures will *not* be +// captured when this technique is used. +try { ws.send('something'); } +catch (e) { /* handle error */ } +``` + +## FAQ + +### How to get the IP address of the client? + +The remote IP address can be obtained from the raw socket. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +wss.on('connection', function connection(ws, req) { + const ip = req.connection.remoteAddress; +}); +``` + +When the server runs behind a proxy like NGINX, the de-facto standard is to use +the `X-Forwarded-For` header. + +```js +wss.on('connection', function connection(ws, req) { + const ip = req.headers['x-forwarded-for']; +}); +``` + +### How to detect and close broken connections? + +Sometimes the link between the server and the client can be interrupted in a +way that keeps both the server and the client unaware of the broken state of the +connection (e.g. when pulling the cord). + +In these cases ping messages can be used as a means to verify that the remote +endpoint is still responsive. + +```js +const WebSocket = require('ws'); + +const wss = new WebSocket.Server({ port: 8080 }); + +function noop() {} + +function heartbeat() { + this.isAlive = true; +} + +wss.on('connection', function connection(ws) { + ws.isAlive = true; + ws.on('pong', heartbeat); +}); + +const interval = setInterval(function ping() { + wss.clients.forEach(function each(ws) { + if (ws.isAlive === false) return ws.terminate(); + + ws.isAlive = false; + ws.ping(noop); + }); +}, 30000); +``` + +Pong messages are automatically sent in response to ping messages as required +by the spec. + +### How to connect via a proxy? + +Use a custom `http.Agent` implementation like [https-proxy-agent][] or +[socks-proxy-agent][]. + +## Changelog + +We're using the GitHub [releases][changelog] for changelog entries. + +## License + +[MIT](LICENSE) + +[https-proxy-agent]: https://github.com/TooTallNate/node-https-proxy-agent +[socks-proxy-agent]: https://github.com/TooTallNate/node-socks-proxy-agent +[client-report]: http://websockets.github.io/ws/autobahn/clients/ +[server-report]: http://websockets.github.io/ws/autobahn/servers/ +[permessage-deflate]: https://tools.ietf.org/html/rfc7692 +[changelog]: https://github.com/websockets/ws/releases +[node-zlib-bug]: https://github.com/nodejs/node/issues/8871 +[node-zlib-deflaterawdocs]: https://nodejs.org/api/zlib.html#zlib_zlib_createdeflateraw_options +[ws-server-options]: https://github.com/websockets/ws/blob/master/doc/ws.md#new-websocketserveroptions-callback diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b8d6be1c9a06bc40ac9ad503a76f3318bc5dade0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/index.js @@ -0,0 +1,9 @@ +'use strict'; + +const WebSocket = require('./lib/websocket'); + +WebSocket.Server = require('./lib/websocket-server'); +WebSocket.Receiver = require('./lib/receiver'); +WebSocket.Sender = require('./lib/sender'); + +module.exports = WebSocket; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/buffer-util.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/buffer-util.js new file mode 100644 index 0000000000000000000000000000000000000000..38e16df3f16a3717eeaa00b782346ddb8945f90c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/buffer-util.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * Merges an array of buffers into a new buffer. + * + * @param {Buffer[]} list The array of buffers to concat + * @param {Number} totalLength The total length of buffers in the list + * @return {Buffer} The resulting buffer + * @public + */ +const concat = (list, totalLength) => { + const target = Buffer.allocUnsafe(totalLength); + var offset = 0; + + for (var i = 0; i < list.length; i++) { + const buf = list[i]; + buf.copy(target, offset); + offset += buf.length; + } + + return target; +}; + +try { + const bufferUtil = require('bufferutil'); + + module.exports = Object.assign({ concat }, bufferUtil.BufferUtil || bufferUtil); +} catch (e) /* istanbul ignore next */ { + /** + * Masks a buffer using the given mask. + * + * @param {Buffer} source The buffer to mask + * @param {Buffer} mask The mask to use + * @param {Buffer} output The buffer where to store the result + * @param {Number} offset The offset at which to start writing + * @param {Number} length The number of bytes to mask. + * @public + */ + const mask = (source, mask, output, offset, length) => { + for (var i = 0; i < length; i++) { + output[offset + i] = source[i] ^ mask[i & 3]; + } + }; + + /** + * Unmasks a buffer using the given mask. + * + * @param {Buffer} buffer The buffer to unmask + * @param {Buffer} mask The mask to use + * @public + */ + const unmask = (buffer, mask) => { + // Required until https://github.com/nodejs/node/issues/9006 is resolved. + const length = buffer.length; + for (var i = 0; i < length; i++) { + buffer[i] ^= mask[i & 3]; + } + }; + + module.exports = { concat, mask, unmask }; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/constants.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/constants.js new file mode 100644 index 0000000000000000000000000000000000000000..4082981f89d2edc44742f51ce0602a5ce9df4bb0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/constants.js @@ -0,0 +1,10 @@ +'use strict'; + +module.exports = { + BINARY_TYPES: ['nodebuffer', 'arraybuffer', 'fragments'], + GUID: '258EAFA5-E914-47DA-95CA-C5AB0DC85B11', + kStatusCode: Symbol('status-code'), + kWebSocket: Symbol('websocket'), + EMPTY_BUFFER: Buffer.alloc(0), + NOOP: () => {} +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/event-target.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/event-target.js new file mode 100644 index 0000000000000000000000000000000000000000..574e9080e2ee2a90dd67734ab69286336855fbea --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/event-target.js @@ -0,0 +1,170 @@ +'use strict'; + +/** + * Class representing an event. + * + * @private + */ +class Event { + /** + * Create a new `Event`. + * + * @param {String} type The name of the event + * @param {Object} target A reference to the target to which the event was dispatched + */ + constructor (type, target) { + this.target = target; + this.type = type; + } +} + +/** + * Class representing a message event. + * + * @extends Event + * @private + */ +class MessageEvent extends Event { + /** + * Create a new `MessageEvent`. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The received data + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (data, target) { + super('message', target); + + this.data = data; + } +} + +/** + * Class representing a close event. + * + * @extends Event + * @private + */ +class CloseEvent extends Event { + /** + * Create a new `CloseEvent`. + * + * @param {Number} code The status code explaining why the connection is being closed + * @param {String} reason A human-readable string explaining why the connection is closing + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (code, reason, target) { + super('close', target); + + this.wasClean = target._closeFrameReceived && target._closeFrameSent; + this.reason = reason; + this.code = code; + } +} + +/** + * Class representing an open event. + * + * @extends Event + * @private + */ +class OpenEvent extends Event { + /** + * Create a new `OpenEvent`. + * + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (target) { + super('open', target); + } +} + +/** + * Class representing an error event. + * + * @extends Event + * @private + */ +class ErrorEvent extends Event { + /** + * Create a new `ErrorEvent`. + * + * @param {Object} error The error that generated this event + * @param {WebSocket} target A reference to the target to which the event was dispatched + */ + constructor (error, target) { + super('error', target); + + this.message = error.message; + this.error = error; + } +} + +/** + * This provides methods for emulating the `EventTarget` interface. It's not + * meant to be used directly. + * + * @mixin + */ +const EventTarget = { + /** + * Register an event listener. + * + * @param {String} method A string representing the event type to listen for + * @param {Function} listener The listener to add + * @public + */ + addEventListener (method, listener) { + if (typeof listener !== 'function') return; + + function onMessage (data) { + listener.call(this, new MessageEvent(data, this)); + } + + function onClose (code, message) { + listener.call(this, new CloseEvent(code, message, this)); + } + + function onError (error) { + listener.call(this, new ErrorEvent(error, this)); + } + + function onOpen () { + listener.call(this, new OpenEvent(this)); + } + + if (method === 'message') { + onMessage._listener = listener; + this.on(method, onMessage); + } else if (method === 'close') { + onClose._listener = listener; + this.on(method, onClose); + } else if (method === 'error') { + onError._listener = listener; + this.on(method, onError); + } else if (method === 'open') { + onOpen._listener = listener; + this.on(method, onOpen); + } else { + this.on(method, listener); + } + }, + + /** + * Remove an event listener. + * + * @param {String} method A string representing the event type to remove + * @param {Function} listener The listener to remove + * @public + */ + removeEventListener (method, listener) { + const listeners = this.listeners(method); + + for (var i = 0; i < listeners.length; i++) { + if (listeners[i] === listener || listeners[i]._listener === listener) { + this.removeListener(method, listeners[i]); + } + } + } +}; + +module.exports = EventTarget; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/extension.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/extension.js new file mode 100644 index 0000000000000000000000000000000000000000..3f48d75174031a06adb47b794e6bcaccbd66fc22 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/extension.js @@ -0,0 +1,211 @@ +'use strict'; + +// +// Allowed token characters: +// +// '!', '#', '$', '%', '&', ''', '*', '+', '-', +// '.', 0-9, A-Z, '^', '_', '`', a-z, '|', '~' +// +// tokenChars[32] === 0 // ' ' +// tokenChars[33] === 1 // '!' +// tokenChars[34] === 0 // '"' +// ... +// +const tokenChars = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 0 - 15 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 16 - 31 + 0, 1, 0, 1, 1, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, // 32 - 47 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, // 48 - 63 + 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 64 - 79 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 1, 1, // 80 - 95 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 96 - 111 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 0, 1, 0 // 112 - 127 +]; + +/** + * Adds an offer to the map of extension offers or a parameter to the map of + * parameters. + * + * @param {Object} dest The map of extension offers or parameters + * @param {String} name The extension or parameter name + * @param {(Object|Boolean|String)} elem The extension parameters or the + * parameter value + * @private + */ +function push (dest, name, elem) { + if (Object.prototype.hasOwnProperty.call(dest, name)) dest[name].push(elem); + else dest[name] = [elem]; +} + +/** + * Parses the `Sec-WebSocket-Extensions` header into an object. + * + * @param {String} header The field value of the header + * @return {Object} The parsed object + * @public + */ +function parse (header) { + const offers = {}; + + if (header === undefined || header === '') return offers; + + var params = {}; + var mustUnescape = false; + var isEscaping = false; + var inQuotes = false; + var extensionName; + var paramName; + var start = -1; + var end = -1; + + for (var i = 0; i < header.length; i++) { + const code = header.charCodeAt(i); + + if (extensionName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20/* ' ' */|| code === 0x09/* '\t' */) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b/* ';' */ || code === 0x2c/* ',' */) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + const name = header.slice(start, end); + if (code === 0x2c) { + push(offers, name, params); + params = {}; + } else { + extensionName = name; + } + + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (paramName === undefined) { + if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x20 || code === 0x09) { + if (end === -1 && start !== -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + push(params, header.slice(start, end), true); + if (code === 0x2c) { + push(offers, extensionName, params); + params = {}; + extensionName = undefined; + } + + start = end = -1; + } else if (code === 0x3d/* '=' */&& start !== -1 && end === -1) { + paramName = header.slice(start, i); + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else { + // + // The value of a quoted-string after unescaping must conform to the + // token ABNF, so only token characters are valid. + // Ref: https://tools.ietf.org/html/rfc6455#section-9.1 + // + if (isEscaping) { + if (tokenChars[code] !== 1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + if (start === -1) start = i; + else if (!mustUnescape) mustUnescape = true; + isEscaping = false; + } else if (inQuotes) { + if (tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (code === 0x22/* '"' */ && start !== -1) { + inQuotes = false; + end = i; + } else if (code === 0x5c/* '\' */) { + isEscaping = true; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } else if (code === 0x22 && header.charCodeAt(i - 1) === 0x3d) { + inQuotes = true; + } else if (end === -1 && tokenChars[code] === 1) { + if (start === -1) start = i; + } else if (start !== -1 && (code === 0x20 || code === 0x09)) { + if (end === -1) end = i; + } else if (code === 0x3b || code === 0x2c) { + if (start === -1) { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + + if (end === -1) end = i; + var value = header.slice(start, end); + if (mustUnescape) { + value = value.replace(/\\/g, ''); + mustUnescape = false; + } + push(params, paramName, value); + if (code === 0x2c) { + push(offers, extensionName, params); + params = {}; + extensionName = undefined; + } + + paramName = undefined; + start = end = -1; + } else { + throw new SyntaxError(`Unexpected character at index ${i}`); + } + } + } + + if (start === -1 || inQuotes) { + throw new SyntaxError('Unexpected end of input'); + } + + if (end === -1) end = i; + const token = header.slice(start, end); + if (extensionName === undefined) { + push(offers, token, {}); + } else { + if (paramName === undefined) { + push(params, token, true); + } else if (mustUnescape) { + push(params, paramName, token.replace(/\\/g, '')); + } else { + push(params, paramName, token); + } + push(offers, extensionName, params); + } + + return offers; +} + +/** + * Builds the `Sec-WebSocket-Extensions` header field value. + * + * @param {Object} extensions The map of extensions and parameters to format + * @return {String} A string representing the given object + * @public + */ +function format (extensions) { + return Object.keys(extensions).map((extension) => { + var configurations = extensions[extension]; + if (!Array.isArray(configurations)) configurations = [configurations]; + return configurations.map((params) => { + return [extension].concat(Object.keys(params).map((k) => { + var values = params[k]; + if (!Array.isArray(values)) values = [values]; + return values.map((v) => v === true ? k : `${k}=${v}`).join('; '); + })).join('; '); + }).join(', '); + }).join(', '); +} + +module.exports = { format, parse }; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/permessage-deflate.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/permessage-deflate.js new file mode 100644 index 0000000000000000000000000000000000000000..0d54f035b63025c33284a2e02583c17288120c76 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/permessage-deflate.js @@ -0,0 +1,516 @@ +'use strict'; + +const Limiter = require('async-limiter'); +const zlib = require('zlib'); + +const bufferUtil = require('./buffer-util'); +const constants = require('./constants'); + +const TRAILER = Buffer.from([0x00, 0x00, 0xff, 0xff]); +const EMPTY_BLOCK = Buffer.from([0x00]); + +const kPerMessageDeflate = Symbol('permessage-deflate'); +const kWriteInProgress = Symbol('write-in-progress'); +const kPendingClose = Symbol('pending-close'); +const kTotalLength = Symbol('total-length'); +const kCallback = Symbol('callback'); +const kBuffers = Symbol('buffers'); +const kError = Symbol('error'); + +// +// We limit zlib concurrency, which prevents severe memory fragmentation +// as documented in https://github.com/nodejs/node/issues/8871#issuecomment-250915913 +// and https://github.com/websockets/ws/issues/1202 +// +// Intentionally global; it's the global thread pool that's an issue. +// +let zlibLimiter; + +/** + * permessage-deflate implementation. + */ +class PerMessageDeflate { + /** + * Creates a PerMessageDeflate instance. + * + * @param {Object} options Configuration options + * @param {Boolean} options.serverNoContextTakeover Request/accept disabling + * of server context takeover + * @param {Boolean} options.clientNoContextTakeover Advertise/acknowledge + * disabling of client context takeover + * @param {(Boolean|Number)} options.serverMaxWindowBits Request/confirm the + * use of a custom server window size + * @param {(Boolean|Number)} options.clientMaxWindowBits Advertise support + * for, or request, a custom client window size + * @param {Object} options.zlibDeflateOptions Options to pass to zlib on deflate + * @param {Object} options.zlibInflateOptions Options to pass to zlib on inflate + * @param {Number} options.threshold Size (in bytes) below which messages + * should not be compressed + * @param {Number} options.concurrencyLimit The number of concurrent calls to + * zlib + * @param {Boolean} isServer Create the instance in either server or client + * mode + * @param {Number} maxPayload The maximum allowed message length + */ + constructor (options, isServer, maxPayload) { + this._maxPayload = maxPayload | 0; + this._options = options || {}; + this._threshold = this._options.threshold !== undefined + ? this._options.threshold + : 1024; + this._isServer = !!isServer; + this._deflate = null; + this._inflate = null; + + this.params = null; + + if (!zlibLimiter) { + const concurrency = this._options.concurrencyLimit !== undefined + ? this._options.concurrencyLimit + : 10; + zlibLimiter = new Limiter({ concurrency }); + } + } + + /** + * @type {String} + */ + static get extensionName () { + return 'permessage-deflate'; + } + + /** + * Create an extension negotiation offer. + * + * @return {Object} Extension parameters + * @public + */ + offer () { + const params = {}; + + if (this._options.serverNoContextTakeover) { + params.server_no_context_takeover = true; + } + if (this._options.clientNoContextTakeover) { + params.client_no_context_takeover = true; + } + if (this._options.serverMaxWindowBits) { + params.server_max_window_bits = this._options.serverMaxWindowBits; + } + if (this._options.clientMaxWindowBits) { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } else if (this._options.clientMaxWindowBits == null) { + params.client_max_window_bits = true; + } + + return params; + } + + /** + * Accept an extension negotiation offer/response. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Object} Accepted configuration + * @public + */ + accept (configurations) { + configurations = this.normalizeParams(configurations); + + this.params = this._isServer + ? this.acceptAsServer(configurations) + : this.acceptAsClient(configurations); + + return this.params; + } + + /** + * Releases all resources used by the extension. + * + * @public + */ + cleanup () { + if (this._inflate) { + if (this._inflate[kWriteInProgress]) { + this._inflate[kPendingClose] = true; + } else { + this._inflate.close(); + this._inflate = null; + } + } + if (this._deflate) { + if (this._deflate[kWriteInProgress]) { + this._deflate[kPendingClose] = true; + } else { + this._deflate.close(); + this._deflate = null; + } + } + } + + /** + * Accept an extension negotiation offer. + * + * @param {Array} offers The extension negotiation offers + * @return {Object} Accepted configuration + * @private + */ + acceptAsServer (offers) { + const opts = this._options; + const accepted = offers.find((params) => { + if ( + (opts.serverNoContextTakeover === false && + params.server_no_context_takeover) || + (params.server_max_window_bits && + (opts.serverMaxWindowBits === false || + (typeof opts.serverMaxWindowBits === 'number' && + opts.serverMaxWindowBits > params.server_max_window_bits))) || + (typeof opts.clientMaxWindowBits === 'number' && + !params.client_max_window_bits) + ) { + return false; + } + + return true; + }); + + if (!accepted) { + throw new Error('None of the extension offers can be accepted'); + } + + if (opts.serverNoContextTakeover) { + accepted.server_no_context_takeover = true; + } + if (opts.clientNoContextTakeover) { + accepted.client_no_context_takeover = true; + } + if (typeof opts.serverMaxWindowBits === 'number') { + accepted.server_max_window_bits = opts.serverMaxWindowBits; + } + if (typeof opts.clientMaxWindowBits === 'number') { + accepted.client_max_window_bits = opts.clientMaxWindowBits; + } else if ( + accepted.client_max_window_bits === true || + opts.clientMaxWindowBits === false + ) { + delete accepted.client_max_window_bits; + } + + return accepted; + } + + /** + * Accept the extension negotiation response. + * + * @param {Array} response The extension negotiation response + * @return {Object} Accepted configuration + * @private + */ + acceptAsClient (response) { + const params = response[0]; + + if ( + this._options.clientNoContextTakeover === false && + params.client_no_context_takeover + ) { + throw new Error('Unexpected parameter "client_no_context_takeover"'); + } + + if (!params.client_max_window_bits) { + if (typeof this._options.clientMaxWindowBits === 'number') { + params.client_max_window_bits = this._options.clientMaxWindowBits; + } + } else if ( + this._options.clientMaxWindowBits === false || + (typeof this._options.clientMaxWindowBits === 'number' && + params.client_max_window_bits > this._options.clientMaxWindowBits) + ) { + throw new Error( + 'Unexpected or invalid parameter "client_max_window_bits"' + ); + } + + return params; + } + + /** + * Normalize parameters. + * + * @param {Array} configurations The extension negotiation offers/reponse + * @return {Array} The offers/response with normalized parameters + * @private + */ + normalizeParams (configurations) { + configurations.forEach((params) => { + Object.keys(params).forEach((key) => { + var value = params[key]; + + if (value.length > 1) { + throw new Error(`Parameter "${key}" must have only a single value`); + } + + value = value[0]; + + if (key === 'client_max_window_bits') { + if (value !== true) { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if (!this._isServer) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else if (key === 'server_max_window_bits') { + const num = +value; + if (!Number.isInteger(num) || num < 8 || num > 15) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + value = num; + } else if ( + key === 'client_no_context_takeover' || + key === 'server_no_context_takeover' + ) { + if (value !== true) { + throw new TypeError( + `Invalid value for parameter "${key}": ${value}` + ); + } + } else { + throw new Error(`Unknown parameter "${key}"`); + } + + params[key] = value; + }); + }); + + return configurations; + } + + /** + * Decompress data. Concurrency limited by async-limiter. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + decompress (data, fin, callback) { + zlibLimiter.push((done) => { + this._decompress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Compress data. Concurrency limited by async-limiter. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @public + */ + compress (data, fin, callback) { + zlibLimiter.push((done) => { + this._compress(data, fin, (err, result) => { + done(); + callback(err, result); + }); + }); + } + + /** + * Decompress data. + * + * @param {Buffer} data Compressed data + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _decompress (data, fin, callback) { + const endpoint = this._isServer ? 'client' : 'server'; + + if (!this._inflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._inflate = zlib.createInflateRaw( + Object.assign({}, this._options.zlibInflateOptions, { windowBits }) + ); + this._inflate[kPerMessageDeflate] = this; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + this._inflate.on('error', inflateOnError); + this._inflate.on('data', inflateOnData); + } + + this._inflate[kCallback] = callback; + this._inflate[kWriteInProgress] = true; + + this._inflate.write(data); + if (fin) this._inflate.write(TRAILER); + + this._inflate.flush(() => { + const err = this._inflate[kError]; + + if (err) { + this._inflate.close(); + this._inflate = null; + callback(err); + return; + } + + const data = bufferUtil.concat( + this._inflate[kBuffers], + this._inflate[kTotalLength] + ); + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._inflate[kPendingClose] + ) { + this._inflate.close(); + this._inflate = null; + } else { + this._inflate[kWriteInProgress] = false; + this._inflate[kTotalLength] = 0; + this._inflate[kBuffers] = []; + } + + callback(null, data); + }); + } + + /** + * Compress data. + * + * @param {Buffer} data Data to compress + * @param {Boolean} fin Specifies whether or not this is the last fragment + * @param {Function} callback Callback + * @private + */ + _compress (data, fin, callback) { + if (!data || data.length === 0) { + process.nextTick(callback, null, EMPTY_BLOCK); + return; + } + + const endpoint = this._isServer ? 'server' : 'client'; + + if (!this._deflate) { + const key = `${endpoint}_max_window_bits`; + const windowBits = typeof this.params[key] !== 'number' + ? zlib.Z_DEFAULT_WINDOWBITS + : this.params[key]; + + this._deflate = zlib.createDeflateRaw( + Object.assign( + // TODO deprecate memLevel/level and recommend zlibDeflateOptions instead + { + memLevel: this._options.memLevel, + level: this._options.level + }, + this._options.zlibDeflateOptions, + { windowBits } + ) + ); + + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + + // + // `zlib.DeflateRaw` emits an `'error'` event only when an attempt to use + // it is made after it has already been closed. This cannot happen here, + // so we only add a listener for the `'data'` event. + // + this._deflate.on('data', deflateOnData); + } + + this._deflate[kWriteInProgress] = true; + + this._deflate.write(data); + this._deflate.flush(zlib.Z_SYNC_FLUSH, () => { + var data = bufferUtil.concat( + this._deflate[kBuffers], + this._deflate[kTotalLength] + ); + + if (fin) data = data.slice(0, data.length - 4); + + if ( + (fin && this.params[`${endpoint}_no_context_takeover`]) || + this._deflate[kPendingClose] + ) { + this._deflate.close(); + this._deflate = null; + } else { + this._deflate[kWriteInProgress] = false; + this._deflate[kTotalLength] = 0; + this._deflate[kBuffers] = []; + } + + callback(null, data); + }); + } +} + +module.exports = PerMessageDeflate; + +/** + * The listener of the `zlib.DeflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function deflateOnData (chunk) { + this[kBuffers].push(chunk); + this[kTotalLength] += chunk.length; +} + +/** + * The listener of the `zlib.InflateRaw` stream `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function inflateOnData (chunk) { + this[kTotalLength] += chunk.length; + + if ( + this[kPerMessageDeflate]._maxPayload < 1 || + this[kTotalLength] <= this[kPerMessageDeflate]._maxPayload + ) { + this[kBuffers].push(chunk); + return; + } + + this[kError] = new RangeError('Max payload size exceeded'); + this[kError][constants.kStatusCode] = 1009; + this.removeListener('data', inflateOnData); + this.reset(); +} + +/** + * The listener of the `zlib.InflateRaw` stream `'error'` event. + * + * @param {Error} err The emitted error + * @private + */ +function inflateOnError (err) { + // + // There is no need to call `Zlib#close()` as the handle is automatically + // closed when an error is emitted. + // + this[kPerMessageDeflate]._inflate = null; + err[constants.kStatusCode] = 1007; + this[kCallback](err); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/receiver.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/receiver.js new file mode 100644 index 0000000000000000000000000000000000000000..ab2d68c8d420889027b997fb3af01c02ec0ca3ff --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/receiver.js @@ -0,0 +1,513 @@ +'use strict'; + +const stream = require('stream'); + +const PerMessageDeflate = require('./permessage-deflate'); +const bufferUtil = require('./buffer-util'); +const validation = require('./validation'); +const constants = require('./constants'); + +const GET_INFO = 0; +const GET_PAYLOAD_LENGTH_16 = 1; +const GET_PAYLOAD_LENGTH_64 = 2; +const GET_MASK = 3; +const GET_DATA = 4; +const INFLATING = 5; + +/** + * HyBi Receiver implementation. + * + * @extends stream.Writable + */ +class Receiver extends stream.Writable { + /** + * Creates a Receiver instance. + * + * @param {String} binaryType The type for binary data + * @param {Object} extensions An object containing the negotiated extensions + * @param {Number} maxPayload The maximum allowed message length + */ + constructor (binaryType, extensions, maxPayload) { + super(); + + this._binaryType = binaryType || constants.BINARY_TYPES[0]; + this[constants.kWebSocket] = undefined; + this._extensions = extensions || {}; + this._maxPayload = maxPayload | 0; + + this._bufferedBytes = 0; + this._buffers = []; + + this._compressed = false; + this._payloadLength = 0; + this._mask = undefined; + this._fragmented = 0; + this._masked = false; + this._fin = false; + this._opcode = 0; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragments = []; + + this._state = GET_INFO; + this._loop = false; + } + + /** + * Implements `Writable.prototype._write()`. + * + * @param {Buffer} chunk The chunk of data to write + * @param {String} encoding The character encoding of `chunk` + * @param {Function} cb Callback + */ + _write (chunk, encoding, cb) { + if (this._opcode === 0x08) return cb(); + + this._bufferedBytes += chunk.length; + this._buffers.push(chunk); + this.startLoop(cb); + } + + /** + * Consumes `n` bytes from the buffered data. + * + * @param {Number} n The number of bytes to consume + * @return {Buffer} The consumed bytes + * @private + */ + consume (n) { + this._bufferedBytes -= n; + + if (n === this._buffers[0].length) return this._buffers.shift(); + + if (n < this._buffers[0].length) { + const buf = this._buffers[0]; + this._buffers[0] = buf.slice(n); + return buf.slice(0, n); + } + + const dst = Buffer.allocUnsafe(n); + + do { + const buf = this._buffers[0]; + + if (n >= buf.length) { + this._buffers.shift().copy(dst, dst.length - n); + } else { + buf.copy(dst, dst.length - n, 0, n); + this._buffers[0] = buf.slice(n); + } + + n -= buf.length; + } while (n > 0); + + return dst; + } + + /** + * Starts the parsing loop. + * + * @param {Function} cb Callback + * @private + */ + startLoop (cb) { + var err; + this._loop = true; + + do { + switch (this._state) { + case GET_INFO: + err = this.getInfo(); + break; + case GET_PAYLOAD_LENGTH_16: + err = this.getPayloadLength16(); + break; + case GET_PAYLOAD_LENGTH_64: + err = this.getPayloadLength64(); + break; + case GET_MASK: + this.getMask(); + break; + case GET_DATA: + err = this.getData(cb); + break; + default: // `INFLATING` + this._loop = false; + return; + } + } while (this._loop); + + cb(err); + } + + /** + * Reads the first two bytes of a frame. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getInfo () { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + const buf = this.consume(2); + + if ((buf[0] & 0x30) !== 0x00) { + this._loop = false; + return error(RangeError, 'RSV2 and RSV3 must be clear', true, 1002); + } + + const compressed = (buf[0] & 0x40) === 0x40; + + if (compressed && !this._extensions[PerMessageDeflate.extensionName]) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + this._fin = (buf[0] & 0x80) === 0x80; + this._opcode = buf[0] & 0x0f; + this._payloadLength = buf[1] & 0x7f; + + if (this._opcode === 0x00) { + if (compressed) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + if (!this._fragmented) { + this._loop = false; + return error(RangeError, 'invalid opcode 0', true, 1002); + } + + this._opcode = this._fragmented; + } else if (this._opcode === 0x01 || this._opcode === 0x02) { + if (this._fragmented) { + this._loop = false; + return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); + } + + this._compressed = compressed; + } else if (this._opcode > 0x07 && this._opcode < 0x0b) { + if (!this._fin) { + this._loop = false; + return error(RangeError, 'FIN must be set', true, 1002); + } + + if (compressed) { + this._loop = false; + return error(RangeError, 'RSV1 must be clear', true, 1002); + } + + if (this._payloadLength > 0x7d) { + this._loop = false; + return error( + RangeError, + `invalid payload length ${this._payloadLength}`, + true, + 1002 + ); + } + } else { + this._loop = false; + return error(RangeError, `invalid opcode ${this._opcode}`, true, 1002); + } + + if (!this._fin && !this._fragmented) this._fragmented = this._opcode; + this._masked = (buf[1] & 0x80) === 0x80; + + if (this._payloadLength === 126) this._state = GET_PAYLOAD_LENGTH_16; + else if (this._payloadLength === 127) this._state = GET_PAYLOAD_LENGTH_64; + else return this.haveLength(); + } + + /** + * Gets extended payload length (7+16). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength16 () { + if (this._bufferedBytes < 2) { + this._loop = false; + return; + } + + this._payloadLength = this.consume(2).readUInt16BE(0, true); + return this.haveLength(); + } + + /** + * Gets extended payload length (7+64). + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + getPayloadLength64 () { + if (this._bufferedBytes < 8) { + this._loop = false; + return; + } + + const buf = this.consume(8); + const num = buf.readUInt32BE(0, true); + + // + // The maximum safe integer in JavaScript is 2^53 - 1. An error is returned + // if payload length is greater than this number. + // + if (num > Math.pow(2, 53 - 32) - 1) { + this._loop = false; + return error( + RangeError, + 'Unsupported WebSocket frame: payload length > 2^53 - 1', + false, + 1009 + ); + } + + this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4, true); + return this.haveLength(); + } + + /** + * Payload length has been read. + * + * @return {(RangeError|undefined)} A possible error + * @private + */ + haveLength () { + if (this._payloadLength && this._opcode < 0x08) { + this._totalPayloadLength += this._payloadLength; + if (this._totalPayloadLength > this._maxPayload && this._maxPayload > 0) { + this._loop = false; + return error(RangeError, 'Max payload size exceeded', false, 1009); + } + } + + if (this._masked) this._state = GET_MASK; + else this._state = GET_DATA; + } + + /** + * Reads mask bytes. + * + * @private + */ + getMask () { + if (this._bufferedBytes < 4) { + this._loop = false; + return; + } + + this._mask = this.consume(4); + this._state = GET_DATA; + } + + /** + * Reads data bytes. + * + * @param {Function} cb Callback + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + getData (cb) { + var data = constants.EMPTY_BUFFER; + + if (this._payloadLength) { + if (this._bufferedBytes < this._payloadLength) { + this._loop = false; + return; + } + + data = this.consume(this._payloadLength); + if (this._masked) bufferUtil.unmask(data, this._mask); + } + + if (this._opcode > 0x07) return this.controlMessage(data); + + if (this._compressed) { + this._state = INFLATING; + this.decompress(data, cb); + return; + } + + if (data.length) { + // + // This message is not compressed so its lenght is the sum of the payload + // length of all fragments. + // + this._messageLength = this._totalPayloadLength; + this._fragments.push(data); + } + + return this.dataMessage(); + } + + /** + * Decompresses data. + * + * @param {Buffer} data Compressed data + * @param {Function} cb Callback + * @private + */ + decompress (data, cb) { + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + perMessageDeflate.decompress(data, this._fin, (err, buf) => { + if (err) return cb(err); + + if (buf.length) { + this._messageLength += buf.length; + if (this._messageLength > this._maxPayload && this._maxPayload > 0) { + return cb(error(RangeError, 'Max payload size exceeded', false, 1009)); + } + + this._fragments.push(buf); + } + + const er = this.dataMessage(); + if (er) return cb(er); + + this.startLoop(cb); + }); + } + + /** + * Handles a data message. + * + * @return {(Error|undefined)} A possible error + * @private + */ + dataMessage () { + if (this._fin) { + const messageLength = this._messageLength; + const fragments = this._fragments; + + this._totalPayloadLength = 0; + this._messageLength = 0; + this._fragmented = 0; + this._fragments = []; + + if (this._opcode === 2) { + var data; + + if (this._binaryType === 'nodebuffer') { + data = toBuffer(fragments, messageLength); + } else if (this._binaryType === 'arraybuffer') { + data = toArrayBuffer(toBuffer(fragments, messageLength)); + } else { + data = fragments; + } + + this.emit('message', data); + } else { + const buf = toBuffer(fragments, messageLength); + + if (!validation.isValidUTF8(buf)) { + this._loop = false; + return error(Error, 'invalid UTF-8 sequence', true, 1007); + } + + this.emit('message', buf.toString()); + } + } + + this._state = GET_INFO; + } + + /** + * Handles a control message. + * + * @param {Buffer} data Data to handle + * @return {(Error|RangeError|undefined)} A possible error + * @private + */ + controlMessage (data) { + if (this._opcode === 0x08) { + this._loop = false; + + if (data.length === 0) { + this.emit('conclude', 1005, ''); + this.end(); + } else if (data.length === 1) { + return error(RangeError, 'invalid payload length 1', true, 1002); + } else { + const code = data.readUInt16BE(0, true); + + if (!validation.isValidStatusCode(code)) { + return error(RangeError, `invalid status code ${code}`, true, 1002); + } + + const buf = data.slice(2); + + if (!validation.isValidUTF8(buf)) { + return error(Error, 'invalid UTF-8 sequence', true, 1007); + } + + this.emit('conclude', code, buf.toString()); + this.end(); + } + + return; + } + + if (this._opcode === 0x09) this.emit('ping', data); + else this.emit('pong', data); + + this._state = GET_INFO; + } +} + +module.exports = Receiver; + +/** + * Builds an error object. + * + * @param {(Error|RangeError)} ErrorCtor The error constructor + * @param {String} message The error message + * @param {Boolean} prefix Specifies whether or not to add a default prefix to + * `message` + * @param {Number} statusCode The status code + * @return {(Error|RangeError)} The error + * @private + */ +function error (ErrorCtor, message, prefix, statusCode) { + const err = new ErrorCtor( + prefix ? `Invalid WebSocket frame: ${message}` : message + ); + + Error.captureStackTrace(err, error); + err[constants.kStatusCode] = statusCode; + return err; +} + +/** + * Makes a buffer from a list of fragments. + * + * @param {Buffer[]} fragments The list of fragments composing the message + * @param {Number} messageLength The length of the message + * @return {Buffer} + * @private + */ +function toBuffer (fragments, messageLength) { + if (fragments.length === 1) return fragments[0]; + if (fragments.length > 1) return bufferUtil.concat(fragments, messageLength); + return constants.EMPTY_BUFFER; +} + +/** + * Converts a buffer to an `ArrayBuffer`. + * + * @param {Buffer} The buffer to convert + * @return {ArrayBuffer} Converted buffer + */ +function toArrayBuffer (buf) { + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer; + } + + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/sender.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/sender.js new file mode 100644 index 0000000000000000000000000000000000000000..42cbb890f6e7b41d074eb44bda06a12fb6869f58 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/sender.js @@ -0,0 +1,401 @@ +'use strict'; + +const crypto = require('crypto'); + +const PerMessageDeflate = require('./permessage-deflate'); +const bufferUtil = require('./buffer-util'); +const validation = require('./validation'); +const constants = require('./constants'); + +/** + * HyBi Sender implementation. + */ +class Sender { + /** + * Creates a Sender instance. + * + * @param {net.Socket} socket The connection socket + * @param {Object} extensions An object containing the negotiated extensions + */ + constructor (socket, extensions) { + this._extensions = extensions || {}; + this._socket = socket; + + this._firstFragment = true; + this._compress = false; + + this._bufferedBytes = 0; + this._deflating = false; + this._queue = []; + } + + /** + * Frames a piece of data according to the HyBi WebSocket protocol. + * + * @param {Buffer} data The data to frame + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @return {Buffer[]} The framed data as a list of `Buffer` instances + * @public + */ + static frame (data, options) { + const merge = data.length < 1024 || (options.mask && options.readOnly); + var offset = options.mask ? 6 : 2; + var payloadLength = data.length; + + if (data.length >= 65536) { + offset += 8; + payloadLength = 127; + } else if (data.length > 125) { + offset += 2; + payloadLength = 126; + } + + const target = Buffer.allocUnsafe(merge ? data.length + offset : offset); + + target[0] = options.fin ? options.opcode | 0x80 : options.opcode; + if (options.rsv1) target[0] |= 0x40; + + if (payloadLength === 126) { + target.writeUInt16BE(data.length, 2, true); + } else if (payloadLength === 127) { + target.writeUInt32BE(0, 2, true); + target.writeUInt32BE(data.length, 6, true); + } + + if (!options.mask) { + target[1] = payloadLength; + if (merge) { + data.copy(target, offset); + return [target]; + } + + return [target, data]; + } + + const mask = crypto.randomBytes(4); + + target[1] = payloadLength | 0x80; + target[offset - 4] = mask[0]; + target[offset - 3] = mask[1]; + target[offset - 2] = mask[2]; + target[offset - 1] = mask[3]; + + if (merge) { + bufferUtil.mask(data, mask, target, offset, data.length); + return [target]; + } + + bufferUtil.mask(data, mask, data, 0, data.length); + return [target, data]; + } + + /** + * Sends a close message to the other peer. + * + * @param {(Number|undefined)} code The status code component of the body + * @param {String} data The message component of the body + * @param {Boolean} mask Specifies whether or not to mask the message + * @param {Function} cb Callback + * @public + */ + close (code, data, mask, cb) { + var buf; + + if (code === undefined) { + buf = constants.EMPTY_BUFFER; + } else if (typeof code !== 'number' || !validation.isValidStatusCode(code)) { + throw new TypeError('First argument must be a valid error code number'); + } else if (data === undefined || data === '') { + buf = Buffer.allocUnsafe(2); + buf.writeUInt16BE(code, 0, true); + } else { + buf = Buffer.allocUnsafe(2 + Buffer.byteLength(data)); + buf.writeUInt16BE(code, 0, true); + buf.write(data, 2); + } + + if (this._deflating) { + this.enqueue([this.doClose, buf, mask, cb]); + } else { + this.doClose(buf, mask, cb); + } + } + + /** + * Frames and sends a close message. + * + * @param {Buffer} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @private + */ + doClose (data, mask, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x08, + mask, + readOnly: false + }), cb); + } + + /** + * Sends a ping message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + ping (data, mask, cb) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this._deflating) { + this.enqueue([this.doPing, data, mask, readOnly, cb]); + } else { + this.doPing(data, mask, readOnly, cb); + } + } + + /** + * Frames and sends a ping message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @param {Function} cb Callback + * @private + */ + doPing (data, mask, readOnly, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x09, + mask, + readOnly + }), cb); + } + + /** + * Sends a pong message to the other peer. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + pong (data, mask, cb) { + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + if (this._deflating) { + this.enqueue([this.doPong, data, mask, readOnly, cb]); + } else { + this.doPong(data, mask, readOnly, cb); + } + } + + /** + * Frames and sends a pong message. + * + * @param {*} data The message to send + * @param {Boolean} mask Specifies whether or not to mask `data` + * @param {Boolean} readOnly Specifies whether `data` can be modified + * @param {Function} cb Callback + * @private + */ + doPong (data, mask, readOnly, cb) { + this.sendFrame(Sender.frame(data, { + fin: true, + rsv1: false, + opcode: 0x0a, + mask, + readOnly + }), cb); + } + + /** + * Sends a data message to the other peer. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback + * @public + */ + send (data, options, cb) { + var opcode = options.binary ? 2 : 1; + var rsv1 = options.compress; + var readOnly = true; + + if (!Buffer.isBuffer(data)) { + if (data instanceof ArrayBuffer) { + data = Buffer.from(data); + } else if (ArrayBuffer.isView(data)) { + data = viewToBuffer(data); + } else { + data = Buffer.from(data); + readOnly = false; + } + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + if (this._firstFragment) { + this._firstFragment = false; + if (rsv1 && perMessageDeflate) { + rsv1 = data.length >= perMessageDeflate._threshold; + } + this._compress = rsv1; + } else { + rsv1 = false; + opcode = 0; + } + + if (options.fin) this._firstFragment = true; + + if (perMessageDeflate) { + const opts = { + fin: options.fin, + rsv1, + opcode, + mask: options.mask, + readOnly + }; + + if (this._deflating) { + this.enqueue([this.dispatch, data, this._compress, opts, cb]); + } else { + this.dispatch(data, this._compress, opts, cb); + } + } else { + this.sendFrame(Sender.frame(data, { + fin: options.fin, + rsv1: false, + opcode, + mask: options.mask, + readOnly + }), cb); + } + } + + /** + * Dispatches a data message. + * + * @param {Buffer} data The message to send + * @param {Boolean} compress Specifies whether or not to compress `data` + * @param {Object} options Options object + * @param {Number} options.opcode The opcode + * @param {Boolean} options.readOnly Specifies whether `data` can be modified + * @param {Boolean} options.fin Specifies whether or not to set the FIN bit + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Boolean} options.rsv1 Specifies whether or not to set the RSV1 bit + * @param {Function} cb Callback + * @private + */ + dispatch (data, compress, options, cb) { + if (!compress) { + this.sendFrame(Sender.frame(data, options), cb); + return; + } + + const perMessageDeflate = this._extensions[PerMessageDeflate.extensionName]; + + this._deflating = true; + perMessageDeflate.compress(data, options.fin, (_, buf) => { + options.readOnly = false; + this.sendFrame(Sender.frame(buf, options), cb); + this._deflating = false; + this.dequeue(); + }); + } + + /** + * Executes queued send operations. + * + * @private + */ + dequeue () { + while (!this._deflating && this._queue.length) { + const params = this._queue.shift(); + + this._bufferedBytes -= params[1].length; + params[0].apply(this, params.slice(1)); + } + } + + /** + * Enqueues a send operation. + * + * @param {Array} params Send operation parameters. + * @private + */ + enqueue (params) { + this._bufferedBytes += params[1].length; + this._queue.push(params); + } + + /** + * Sends a frame. + * + * @param {Buffer[]} list The frame to send + * @param {Function} cb Callback + * @private + */ + sendFrame (list, cb) { + if (list.length === 2) { + this._socket.write(list[0]); + this._socket.write(list[1], cb); + } else { + this._socket.write(list[0], cb); + } + } +} + +module.exports = Sender; + +/** + * Converts an `ArrayBuffer` view into a buffer. + * + * @param {(DataView|TypedArray)} view The view to convert + * @return {Buffer} Converted view + * @private + */ +function viewToBuffer (view) { + const buf = Buffer.from(view.buffer); + + if (view.byteLength !== view.buffer.byteLength) { + return buf.slice(view.byteOffset, view.byteOffset + view.byteLength); + } + + return buf; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/validation.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/validation.js new file mode 100644 index 0000000000000000000000000000000000000000..06269fcf1ae7838387a31ed9fdd9ba7056c50e8b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/validation.js @@ -0,0 +1,29 @@ +'use strict'; + +try { + const isValidUTF8 = require('utf-8-validate'); + + exports.isValidUTF8 = typeof isValidUTF8 === 'object' + ? isValidUTF8.Validation.isValidUTF8 // utf-8-validate@<3.0.0 + : isValidUTF8; +} catch (e) /* istanbul ignore next */ { + exports.isValidUTF8 = () => true; +} + +/** + * Checks if a status code is allowed in a close frame. + * + * @param {Number} code The status code + * @return {Boolean} `true` if the status code is valid, else `false` + * @public + */ +exports.isValidStatusCode = (code) => { + return ( + (code >= 1000 && + code <= 1013 && + code !== 1004 && + code !== 1005 && + code !== 1006) || + (code >= 3000 && code <= 4999) + ); +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket-server.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket-server.js new file mode 100644 index 0000000000000000000000000000000000000000..72618d02876c84f085aef2e8a855d850691b3c5f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket-server.js @@ -0,0 +1,350 @@ +'use strict'; + +const EventEmitter = require('events'); +const crypto = require('crypto'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const extension = require('./extension'); +const constants = require('./constants'); +const WebSocket = require('./websocket'); + +/** + * Class representing a WebSocket server. + * + * @extends EventEmitter + */ +class WebSocketServer extends EventEmitter { + /** + * Create a `WebSocketServer` instance. + * + * @param {Object} options Configuration options + * @param {String} options.host The hostname where to bind the server + * @param {Number} options.port The port where to bind the server + * @param {http.Server} options.server A pre-created HTTP/S server to use + * @param {Function} options.verifyClient An hook to reject connections + * @param {Function} options.handleProtocols An hook to handle protocols + * @param {String} options.path Accept only connections matching this path + * @param {Boolean} options.noServer Enable no server mode + * @param {Boolean} options.clientTracking Specifies whether or not to track clients + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {Number} options.maxPayload The maximum allowed message size + * @param {Function} callback A listener for the `listening` event + */ + constructor (options, callback) { + super(); + + options = Object.assign({ + maxPayload: 100 * 1024 * 1024, + perMessageDeflate: false, + handleProtocols: null, + clientTracking: true, + verifyClient: null, + noServer: false, + backlog: null, // use default (511 as implemented in net.js) + server: null, + host: null, + path: null, + port: null + }, options); + + if (options.port == null && !options.server && !options.noServer) { + throw new TypeError( + 'One of the "port", "server", or "noServer" options must be specified' + ); + } + + if (options.port != null) { + this._server = http.createServer((req, res) => { + const body = http.STATUS_CODES[426]; + + res.writeHead(426, { + 'Content-Length': body.length, + 'Content-Type': 'text/plain' + }); + res.end(body); + }); + this._server.listen(options.port, options.host, options.backlog, callback); + } else if (options.server) { + this._server = options.server; + } + + if (this._server) { + this._removeListeners = addListeners(this._server, { + listening: this.emit.bind(this, 'listening'), + error: this.emit.bind(this, 'error'), + upgrade: (req, socket, head) => { + this.handleUpgrade(req, socket, head, (ws) => { + this.emit('connection', ws, req); + }); + } + }); + } + + if (options.perMessageDeflate === true) options.perMessageDeflate = {}; + if (options.clientTracking) this.clients = new Set(); + this.options = options; + } + + /** + * Returns the bound address, the address family name, and port of the server + * as reported by the operating system if listening on an IP socket. + * If the server is listening on a pipe or UNIX domain socket, the name is + * returned as a string. + * + * @return {(Object|String|null)} The address of the server + * @public + */ + address () { + if (this.options.noServer) { + throw new Error('The server is operating in "noServer" mode'); + } + + if (!this._server) return null; + return this._server.address(); + } + + /** + * Close the server. + * + * @param {Function} cb Callback + * @public + */ + close (cb) { + // + // Terminate all associated clients. + // + if (this.clients) { + for (const client of this.clients) client.terminate(); + } + + const server = this._server; + + if (server) { + this._removeListeners(); + this._removeListeners = this._server = null; + + // + // Close the http server if it was internally created. + // + if (this.options.port != null) return server.close(cb); + } + + if (cb) cb(); + } + + /** + * See if a given request should be handled by this server instance. + * + * @param {http.IncomingMessage} req Request object to inspect + * @return {Boolean} `true` if the request is valid, else `false` + * @public + */ + shouldHandle (req) { + if (this.options.path && url.parse(req.url).pathname !== this.options.path) { + return false; + } + + return true; + } + + /** + * Handle a HTTP Upgrade request. + * + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @public + */ + handleUpgrade (req, socket, head, cb) { + socket.on('error', socketOnError); + + const version = +req.headers['sec-websocket-version']; + const extensions = {}; + + if ( + req.method !== 'GET' || req.headers.upgrade.toLowerCase() !== 'websocket' || + !req.headers['sec-websocket-key'] || (version !== 8 && version !== 13) || + !this.shouldHandle(req) + ) { + return abortHandshake(socket, 400); + } + + if (this.options.perMessageDeflate) { + const perMessageDeflate = new PerMessageDeflate( + this.options.perMessageDeflate, + true, + this.options.maxPayload + ); + + try { + const offers = extension.parse( + req.headers['sec-websocket-extensions'] + ); + + if (offers[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept(offers[PerMessageDeflate.extensionName]); + extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + return abortHandshake(socket, 400); + } + } + + // + // Optionally call external client verification handler. + // + if (this.options.verifyClient) { + const info = { + origin: req.headers[`${version === 8 ? 'sec-websocket-origin' : 'origin'}`], + secure: !!(req.connection.authorized || req.connection.encrypted), + req + }; + + if (this.options.verifyClient.length === 2) { + this.options.verifyClient(info, (verified, code, message) => { + if (!verified) return abortHandshake(socket, code || 401, message); + + this.completeUpgrade(extensions, req, socket, head, cb); + }); + return; + } + + if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); + } + + this.completeUpgrade(extensions, req, socket, head, cb); + } + + /** + * Upgrade the connection to WebSocket. + * + * @param {Object} extensions The accepted extensions + * @param {http.IncomingMessage} req The request object + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Function} cb Callback + * @private + */ + completeUpgrade (extensions, req, socket, head, cb) { + // + // Destroy the socket if the client has already sent a FIN packet. + // + if (!socket.readable || !socket.writable) return socket.destroy(); + + const key = crypto.createHash('sha1') + .update(req.headers['sec-websocket-key'] + constants.GUID, 'binary') + .digest('base64'); + + const headers = [ + 'HTTP/1.1 101 Switching Protocols', + 'Upgrade: websocket', + 'Connection: Upgrade', + `Sec-WebSocket-Accept: ${key}` + ]; + + const ws = new WebSocket(null); + var protocol = req.headers['sec-websocket-protocol']; + + if (protocol) { + protocol = protocol.trim().split(/ *, */); + + // + // Optionally call external protocol selection handler. + // + if (this.options.handleProtocols) { + protocol = this.options.handleProtocols(protocol, req); + } else { + protocol = protocol[0]; + } + + if (protocol) { + headers.push(`Sec-WebSocket-Protocol: ${protocol}`); + ws.protocol = protocol; + } + } + + if (extensions[PerMessageDeflate.extensionName]) { + const params = extensions[PerMessageDeflate.extensionName].params; + const value = extension.format({ + [PerMessageDeflate.extensionName]: [params] + }); + headers.push(`Sec-WebSocket-Extensions: ${value}`); + ws._extensions = extensions; + } + + // + // Allow external modification/inspection of handshake headers. + // + this.emit('headers', headers, req); + + socket.write(headers.concat('\r\n').join('\r\n')); + socket.removeListener('error', socketOnError); + + ws.setSocket(socket, head, this.options.maxPayload); + + if (this.clients) { + this.clients.add(ws); + ws.on('close', () => this.clients.delete(ws)); + } + + cb(ws); + } +} + +module.exports = WebSocketServer; + +/** + * Add event listeners on an `EventEmitter` using a map of <event, listener> + * pairs. + * + * @param {EventEmitter} server The event emitter + * @param {Object.<String, Function>} map The listeners to add + * @return {Function} A function that will remove the added listeners when called + * @private + */ +function addListeners (server, map) { + for (const event of Object.keys(map)) server.on(event, map[event]); + + return function removeListeners () { + for (const event of Object.keys(map)) { + server.removeListener(event, map[event]); + } + }; +} + +/** + * Handle premature socket errors. + * + * @private + */ +function socketOnError () { + this.destroy(); +} + +/** + * Close the connection when preconditions are not fulfilled. + * + * @param {net.Socket} socket The socket of the upgrade request + * @param {Number} code The HTTP response status code + * @param {String} [message] The HTTP response body + * @private + */ +function abortHandshake (socket, code, message) { + if (socket.writable) { + message = message || http.STATUS_CODES[code]; + socket.write( + `HTTP/1.1 ${code} ${http.STATUS_CODES[code]}\r\n` + + 'Connection: close\r\n' + + 'Content-type: text/html\r\n' + + `Content-Length: ${Buffer.byteLength(message)}\r\n` + + '\r\n' + + message + ); + } + + socket.removeListener('error', socketOnError); + socket.destroy(); +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket.js new file mode 100644 index 0000000000000000000000000000000000000000..87f3606fb2ac81d1ad2dca28e295e1316654a3b1 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/lib/websocket.js @@ -0,0 +1,844 @@ +'use strict'; + +const EventEmitter = require('events'); +const crypto = require('crypto'); +const https = require('https'); +const http = require('http'); +const url = require('url'); + +const PerMessageDeflate = require('./permessage-deflate'); +const EventTarget = require('./event-target'); +const extension = require('./extension'); +const constants = require('./constants'); +const Receiver = require('./receiver'); +const Sender = require('./sender'); + +const readyStates = ['CONNECTING', 'OPEN', 'CLOSING', 'CLOSED']; +const kWebSocket = constants.kWebSocket; +const protocolVersions = [8, 13]; +const closeTimeout = 30 * 1000; // Allow 30 seconds to terminate the connection cleanly. + +/** + * Class representing a WebSocket. + * + * @extends EventEmitter + */ +class WebSocket extends EventEmitter { + /** + * Create a new `WebSocket`. + * + * @param {String} address The URL to which to connect + * @param {(String|String[])} protocols The subprotocols + * @param {Object} options Connection options + */ + constructor (address, protocols, options) { + super(); + + this.readyState = WebSocket.CONNECTING; + this.protocol = ''; + + this._binaryType = constants.BINARY_TYPES[0]; + this._closeFrameReceived = false; + this._closeFrameSent = false; + this._closeMessage = ''; + this._closeTimer = null; + this._closeCode = 1006; + this._extensions = {}; + this._isServer = true; + this._receiver = null; + this._sender = null; + this._socket = null; + + if (address !== null) { + if (!protocols) { + protocols = []; + } else if (typeof protocols === 'string') { + protocols = [protocols]; + } else if (!Array.isArray(protocols)) { + options = protocols; + protocols = []; + } + + initAsClient.call(this, address, protocols, options); + } + } + + get CONNECTING () { return WebSocket.CONNECTING; } + get CLOSING () { return WebSocket.CLOSING; } + get CLOSED () { return WebSocket.CLOSED; } + get OPEN () { return WebSocket.OPEN; } + + /** + * This deviates from the WHATWG interface since ws doesn't support the required + * default "blob" type (instead we define a custom "nodebuffer" type). + * + * @type {String} + */ + get binaryType () { + return this._binaryType; + } + + set binaryType (type) { + if (constants.BINARY_TYPES.indexOf(type) < 0) return; + + this._binaryType = type; + + // + // Allow to change `binaryType` on the fly. + // + if (this._receiver) this._receiver._binaryType = type; + } + + /** + * @type {Number} + */ + get bufferedAmount () { + if (!this._socket) return 0; + + // + // `socket.bufferSize` is `undefined` if the socket is closed. + // + return (this._socket.bufferSize || 0) + this._sender._bufferedBytes; + } + + /** + * @type {String} + */ + get extensions () { + return Object.keys(this._extensions).join(); + } + + /** + * Set up the socket and the internal resources. + * + * @param {net.Socket} socket The network socket between the server and client + * @param {Buffer} head The first packet of the upgraded stream + * @param {Number} maxPayload The maximum allowed message size + * @private + */ + setSocket (socket, head, maxPayload) { + const receiver = new Receiver( + this._binaryType, + this._extensions, + maxPayload + ); + + this._sender = new Sender(socket, this._extensions); + this._receiver = receiver; + this._socket = socket; + + receiver[kWebSocket] = this; + socket[kWebSocket] = this; + + receiver.on('conclude', receiverOnConclude); + receiver.on('drain', receiverOnDrain); + receiver.on('error', receiverOnError); + receiver.on('message', receiverOnMessage); + receiver.on('ping', receiverOnPing); + receiver.on('pong', receiverOnPong); + + socket.setTimeout(0); + socket.setNoDelay(); + + if (head.length > 0) socket.unshift(head); + + socket.on('close', socketOnClose); + socket.on('data', socketOnData); + socket.on('end', socketOnEnd); + socket.on('error', socketOnError); + + this.readyState = WebSocket.OPEN; + this.emit('open'); + } + + /** + * Emit the `'close'` event. + * + * @private + */ + emitClose () { + this.readyState = WebSocket.CLOSED; + + if (!this._socket) { + this.emit('close', this._closeCode, this._closeMessage); + return; + } + + if (this._extensions[PerMessageDeflate.extensionName]) { + this._extensions[PerMessageDeflate.extensionName].cleanup(); + } + + this._receiver.removeAllListeners(); + this.emit('close', this._closeCode, this._closeMessage); + } + + /** + * Start a closing handshake. + * + * +----------+ +-----------+ +----------+ + * - - -|ws.close()|-->|close frame|-->|ws.close()|- - - + * | +----------+ +-----------+ +----------+ | + * +----------+ +-----------+ | + * CLOSING |ws.close()|<--|close frame|<--+-----+ CLOSING + * +----------+ +-----------+ | + * | | | +---+ | + * +------------------------+-->|fin| - - - - + * | +---+ | +---+ + * - - - - -|fin|<---------------------+ + * +---+ + * + * @param {Number} code Status code explaining why the connection is closing + * @param {String} data A string explaining why the connection is closing + * @public + */ + close (code, data) { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this.readyState === WebSocket.CLOSING) { + if (this._closeFrameSent && this._closeFrameReceived) this._socket.end(); + return; + } + + this.readyState = WebSocket.CLOSING; + this._sender.close(code, data, !this._isServer, (err) => { + // + // This error is handled by the `'error'` listener on the socket. We only + // want to know if the close frame has been sent here. + // + if (err) return; + + this._closeFrameSent = true; + + if (this._socket.writable) { + if (this._closeFrameReceived) this._socket.end(); + + // + // Ensure that the connection is closed even if the closing handshake + // fails. + // + this._closeTimer = setTimeout( + this._socket.destroy.bind(this._socket), + closeTimeout + ); + } + }); + } + + /** + * Send a ping. + * + * @param {*} data The data to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Function} cb Callback which is executed when the ping is sent + * @public + */ + ping (data, mask, cb) { + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.ping(data || constants.EMPTY_BUFFER, mask, cb); + } + + /** + * Send a pong. + * + * @param {*} data The data to send + * @param {Boolean} mask Indicates whether or not to mask `data` + * @param {Function} cb Callback which is executed when the pong is sent + * @public + */ + pong (data, mask, cb) { + if (typeof data === 'function') { + cb = data; + data = mask = undefined; + } else if (typeof mask === 'function') { + cb = mask; + mask = undefined; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + if (mask === undefined) mask = !this._isServer; + this._sender.pong(data || constants.EMPTY_BUFFER, mask, cb); + } + + /** + * Send a data message. + * + * @param {*} data The message to send + * @param {Object} options Options object + * @param {Boolean} options.compress Specifies whether or not to compress `data` + * @param {Boolean} options.binary Specifies whether `data` is binary or text + * @param {Boolean} options.fin Specifies whether the fragment is the last one + * @param {Boolean} options.mask Specifies whether or not to mask `data` + * @param {Function} cb Callback which is executed when data is written out + * @public + */ + send (data, options, cb) { + if (typeof options === 'function') { + cb = options; + options = {}; + } + + if (this.readyState !== WebSocket.OPEN) { + const err = new Error( + `WebSocket is not open: readyState ${this.readyState} ` + + `(${readyStates[this.readyState]})` + ); + + if (cb) return cb(err); + throw err; + } + + if (typeof data === 'number') data = data.toString(); + + const opts = Object.assign({ + binary: typeof data !== 'string', + mask: !this._isServer, + compress: true, + fin: true + }, options); + + if (!this._extensions[PerMessageDeflate.extensionName]) { + opts.compress = false; + } + + this._sender.send(data || constants.EMPTY_BUFFER, opts, cb); + } + + /** + * Forcibly close the connection. + * + * @public + */ + terminate () { + if (this.readyState === WebSocket.CLOSED) return; + if (this.readyState === WebSocket.CONNECTING) { + const msg = 'WebSocket was closed before the connection was established'; + return abortHandshake(this, this._req, msg); + } + + if (this._socket) { + this.readyState = WebSocket.CLOSING; + this._socket.destroy(); + } + } +} + +readyStates.forEach((readyState, i) => { + WebSocket[readyStates[i]] = i; +}); + +// +// Add the `onopen`, `onerror`, `onclose`, and `onmessage` attributes. +// See https://html.spec.whatwg.org/multipage/comms.html#the-websocket-interface +// +['open', 'error', 'close', 'message'].forEach((method) => { + Object.defineProperty(WebSocket.prototype, `on${method}`, { + /** + * Return the listener of the event. + * + * @return {(Function|undefined)} The event listener or `undefined` + * @public + */ + get () { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + if (listeners[i]._listener) return listeners[i]._listener; + } + }, + /** + * Add a listener for the event. + * + * @param {Function} listener The listener to add + * @public + */ + set (listener) { + const listeners = this.listeners(method); + for (var i = 0; i < listeners.length; i++) { + // + // Remove only the listeners added via `addEventListener`. + // + if (listeners[i]._listener) this.removeListener(method, listeners[i]); + } + this.addEventListener(method, listener); + } + }); +}); + +WebSocket.prototype.addEventListener = EventTarget.addEventListener; +WebSocket.prototype.removeEventListener = EventTarget.removeEventListener; + +module.exports = WebSocket; + +/** + * Initialize a WebSocket client. + * + * @param {String} address The URL to which to connect + * @param {String[]} protocols The list of subprotocols + * @param {Object} options Connection options + * @param {String} options.protocol Value of the `Sec-WebSocket-Protocol` header + * @param {(Boolean|Object)} options.perMessageDeflate Enable/disable permessage-deflate + * @param {Number} options.handshakeTimeout Timeout in milliseconds for the handshake request + * @param {String} options.localAddress Local interface to bind for network connections + * @param {Number} options.protocolVersion Value of the `Sec-WebSocket-Version` header + * @param {Object} options.headers An object containing request headers + * @param {String} options.origin Value of the `Origin` or `Sec-WebSocket-Origin` header + * @param {http.Agent} options.agent Use the specified Agent + * @param {String} options.host Value of the `Host` header + * @param {Number} options.family IP address family to use during hostname lookup (4 or 6). + * @param {Function} options.checkServerIdentity A function to validate the server hostname + * @param {Boolean} options.rejectUnauthorized Verify or not the server certificate + * @param {String} options.passphrase The passphrase for the private key or pfx + * @param {String} options.ciphers The ciphers to use or exclude + * @param {String} options.ecdhCurve The curves for ECDH key agreement to use or exclude + * @param {(String|String[]|Buffer|Buffer[])} options.cert The certificate key + * @param {(String|String[]|Buffer|Buffer[])} options.key The private key + * @param {(String|Buffer)} options.pfx The private key, certificate, and CA certs + * @param {(String|String[]|Buffer|Buffer[])} options.ca Trusted certificates + * @private + */ +function initAsClient (address, protocols, options) { + options = Object.assign({ + protocolVersion: protocolVersions[1], + protocol: protocols.join(','), + perMessageDeflate: true, + handshakeTimeout: null, + localAddress: null, + headers: null, + family: null, + origin: null, + agent: null, + host: null, + + // + // SSL options. + // + checkServerIdentity: null, + rejectUnauthorized: null, + passphrase: null, + ciphers: null, + ecdhCurve: null, + cert: null, + key: null, + pfx: null, + ca: null + }, options); + + if (protocolVersions.indexOf(options.protocolVersion) === -1) { + throw new RangeError( + `Unsupported protocol version: ${options.protocolVersion} ` + + `(supported versions: ${protocolVersions.join(', ')})` + ); + } + + this._isServer = false; + this.url = address; + + const serverUrl = url.parse(address); + const isUnixSocket = serverUrl.protocol === 'ws+unix:'; + + if (!serverUrl.host && (!isUnixSocket || !serverUrl.path)) { + throw new Error(`Invalid URL: ${address}`); + } + + const isSecure = serverUrl.protocol === 'wss:' || serverUrl.protocol === 'https:'; + const key = crypto.randomBytes(16).toString('base64'); + const httpObj = isSecure ? https : http; + var perMessageDeflate; + + const requestOptions = { + port: serverUrl.port || (isSecure ? 443 : 80), + host: serverUrl.hostname, + path: '/', + headers: { + 'Sec-WebSocket-Version': options.protocolVersion, + 'Sec-WebSocket-Key': key, + 'Connection': 'Upgrade', + 'Upgrade': 'websocket' + } + }; + + if (options.headers) Object.assign(requestOptions.headers, options.headers); + if (options.perMessageDeflate) { + perMessageDeflate = new PerMessageDeflate( + options.perMessageDeflate !== true ? options.perMessageDeflate : {}, + false + ); + requestOptions.headers['Sec-WebSocket-Extensions'] = extension.format({ + [PerMessageDeflate.extensionName]: perMessageDeflate.offer() + }); + } + if (options.protocol) { + requestOptions.headers['Sec-WebSocket-Protocol'] = options.protocol; + } + if (options.origin) { + if (options.protocolVersion < 13) { + requestOptions.headers['Sec-WebSocket-Origin'] = options.origin; + } else { + requestOptions.headers.Origin = options.origin; + } + } + if (options.host) requestOptions.headers.Host = options.host; + if (serverUrl.auth) requestOptions.auth = serverUrl.auth; + + if (options.localAddress) requestOptions.localAddress = options.localAddress; + if (options.family) requestOptions.family = options.family; + + if (isUnixSocket) { + const parts = serverUrl.path.split(':'); + + requestOptions.socketPath = parts[0]; + requestOptions.path = parts[1]; + } else if (serverUrl.path) { + // + // Make sure that path starts with `/`. + // + if (serverUrl.path.charAt(0) !== '/') { + requestOptions.path = `/${serverUrl.path}`; + } else { + requestOptions.path = serverUrl.path; + } + } + + var agent = options.agent; + + // + // A custom agent is required for these options. + // + if ( + options.rejectUnauthorized != null || + options.checkServerIdentity || + options.passphrase || + options.ciphers || + options.ecdhCurve || + options.cert || + options.key || + options.pfx || + options.ca + ) { + if (options.passphrase) requestOptions.passphrase = options.passphrase; + if (options.ciphers) requestOptions.ciphers = options.ciphers; + if (options.ecdhCurve) requestOptions.ecdhCurve = options.ecdhCurve; + if (options.cert) requestOptions.cert = options.cert; + if (options.key) requestOptions.key = options.key; + if (options.pfx) requestOptions.pfx = options.pfx; + if (options.ca) requestOptions.ca = options.ca; + if (options.checkServerIdentity) { + requestOptions.checkServerIdentity = options.checkServerIdentity; + } + if (options.rejectUnauthorized != null) { + requestOptions.rejectUnauthorized = options.rejectUnauthorized; + } + + if (!agent) agent = new httpObj.Agent(requestOptions); + } + + if (agent) requestOptions.agent = agent; + + var req = this._req = httpObj.get(requestOptions); + + if (options.handshakeTimeout) { + req.setTimeout( + options.handshakeTimeout, + abortHandshake.bind(null, this, req, 'Opening handshake has timed out') + ); + } + + req.on('error', (err) => { + if (this._req.aborted) return; + + req = this._req = null; + this.readyState = WebSocket.CLOSING; + this.emit('error', err); + this.emitClose(); + }); + + req.on('response', (res) => { + if (this.emit('unexpected-response', req, res)) return; + + abortHandshake(this, req, `Unexpected server response: ${res.statusCode}`); + }); + + req.on('upgrade', (res, socket, head) => { + this.emit('upgrade', res); + + // + // The user may have closed the connection from a listener of the `upgrade` + // event. + // + if (this.readyState !== WebSocket.CONNECTING) return; + + req = this._req = null; + + const digest = crypto.createHash('sha1') + .update(key + constants.GUID, 'binary') + .digest('base64'); + + if (res.headers['sec-websocket-accept'] !== digest) { + abortHandshake(this, socket, 'Invalid Sec-WebSocket-Accept header'); + return; + } + + const serverProt = res.headers['sec-websocket-protocol']; + const protList = (options.protocol || '').split(/, */); + var protError; + + if (!options.protocol && serverProt) { + protError = 'Server sent a subprotocol but none was requested'; + } else if (options.protocol && !serverProt) { + protError = 'Server sent no subprotocol'; + } else if (serverProt && protList.indexOf(serverProt) === -1) { + protError = 'Server sent an invalid subprotocol'; + } + + if (protError) { + abortHandshake(this, socket, protError); + return; + } + + if (serverProt) this.protocol = serverProt; + + if (perMessageDeflate) { + try { + const extensions = extension.parse( + res.headers['sec-websocket-extensions'] + ); + + if (extensions[PerMessageDeflate.extensionName]) { + perMessageDeflate.accept( + extensions[PerMessageDeflate.extensionName] + ); + this._extensions[PerMessageDeflate.extensionName] = perMessageDeflate; + } + } catch (err) { + abortHandshake(this, socket, 'Invalid Sec-WebSocket-Extensions header'); + return; + } + } + + this.setSocket(socket, head, 0); + }); +} + +/** + * Abort the handshake and emit an error. + * + * @param {WebSocket} websocket The WebSocket instance + * @param {(http.ClientRequest|net.Socket)} stream The request to abort or the + * socket to destroy + * @param {String} message The error message + * @private + */ +function abortHandshake (websocket, stream, message) { + websocket.readyState = WebSocket.CLOSING; + + const err = new Error(message); + Error.captureStackTrace(err, abortHandshake); + + if (stream.setHeader) { + stream.abort(); + stream.once('abort', websocket.emitClose.bind(websocket)); + websocket.emit('error', err); + } else { + stream.destroy(err); + stream.once('error', websocket.emit.bind(websocket, 'error')); + stream.once('close', websocket.emitClose.bind(websocket)); + } +} + +/** + * The listener of the `Receiver` `'conclude'` event. + * + * @param {Number} code The status code + * @param {String} reason The reason for closing + * @private + */ +function receiverOnConclude (code, reason) { + const websocket = this[kWebSocket]; + + websocket._socket.removeListener('data', socketOnData); + websocket._socket.resume(); + + websocket._closeFrameReceived = true; + websocket._closeMessage = reason; + websocket._closeCode = code; + + if (code === 1005) websocket.close(); + else websocket.close(code, reason); +} + +/** + * The listener of the `Receiver` `'drain'` event. + * + * @private + */ +function receiverOnDrain () { + this[kWebSocket]._socket.resume(); +} + +/** + * The listener of the `Receiver` `'error'` event. + * + * @param {(RangeError|Error)} err The emitted error + * @private + */ +function receiverOnError (err) { + const websocket = this[kWebSocket]; + + websocket.readyState = WebSocket.CLOSING; + websocket._closeCode = err[constants.kStatusCode]; + websocket.emit('error', err); + websocket._socket.destroy(); +} + +/** + * The listener of the `Receiver` `'finish'` event. + * + * @private + */ +function receiverOnFinish () { + this[kWebSocket].emitClose(); +} + +/** + * The listener of the `Receiver` `'message'` event. + * + * @param {(String|Buffer|ArrayBuffer|Buffer[])} data The message + * @private + */ +function receiverOnMessage (data) { + this[kWebSocket].emit('message', data); +} + +/** + * The listener of the `Receiver` `'ping'` event. + * + * @param {Buffer} data The data included in the ping frame + * @private + */ +function receiverOnPing (data) { + const websocket = this[kWebSocket]; + + websocket.pong(data, !websocket._isServer, constants.NOOP); + websocket.emit('ping', data); +} + +/** + * The listener of the `Receiver` `'pong'` event. + * + * @param {Buffer} data The data included in the pong frame + * @private + */ +function receiverOnPong (data) { + this[kWebSocket].emit('pong', data); +} + +/** + * The listener of the `net.Socket` `'close'` event. + * + * @private + */ +function socketOnClose () { + const websocket = this[kWebSocket]; + + this.removeListener('close', socketOnClose); + this.removeListener('data', socketOnData); + this.removeListener('end', socketOnEnd); + this[kWebSocket] = undefined; + + websocket.readyState = WebSocket.CLOSING; + + // + // The close frame might not have been received or the `'end'` event emitted, + // for example, if the socket was destroyed due to an error. Ensure that the + // `receiver` stream is closed after writing any remaining buffered data to + // it. + // + websocket._socket.read(); + websocket._receiver.end(); + + clearTimeout(websocket._closeTimer); + + if ( + websocket._receiver._writableState.finished || + websocket._receiver._writableState.errorEmitted + ) { + websocket.emitClose(); + } else { + websocket._receiver.on('error', receiverOnFinish); + websocket._receiver.on('finish', receiverOnFinish); + } +} + +/** + * The listener of the `net.Socket` `'data'` event. + * + * @param {Buffer} chunk A chunk of data + * @private + */ +function socketOnData (chunk) { + if (!this[kWebSocket]._receiver.write(chunk)) { + this.pause(); + } +} + +/** + * The listener of the `net.Socket` `'end'` event. + * + * @private + */ +function socketOnEnd () { + const websocket = this[kWebSocket]; + + websocket.readyState = WebSocket.CLOSING; + websocket._receiver.end(); + this.end(); +} + +/** + * The listener of the `net.Socket` `'error'` event. + * + * @private + */ +function socketOnError () { + const websocket = this[kWebSocket]; + + this.removeListener('error', socketOnError); + this.on('error', constants.NOOP); + + if (websocket) { + websocket.readyState = WebSocket.CLOSING; + this.destroy(); + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/package.json new file mode 100644 index 0000000000000000000000000000000000000000..50adda8a2f659d7f48045cb5585567d03cfdf41c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/ws/package.json @@ -0,0 +1,79 @@ +{ + "_from": "ws", + "_id": "ws@5.0.0", + "_inBundle": false, + "_integrity": "sha512-XXG4S0b771C68AeTHebBsJJBZMguxj7Em+D657RViuj6ppRd3tfuOhIK8eGwZGNb76C8MjQfCTfH2NN50rJN4w==", + "_location": "/ws", + "_phantomChildren": {}, + "_requested": { + "type": "tag", + "registry": true, + "raw": "ws", + "name": "ws", + "escapedName": "ws", + "rawSpec": "", + "saveSpec": null, + "fetchSpec": "latest" + }, + "_requiredBy": [ + "#USER", + "/" + ], + "_resolved": "https://registry.npmjs.org/ws/-/ws-5.0.0.tgz", + "_shasum": "fb4ede3fddcff99b157d292a1069ace8d6e04db9", + "_spec": "ws", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts", + "author": { + "name": "Einar Otto Stangvik", + "email": "einaros@gmail.com", + "url": "http://2x.io" + }, + "bugs": { + "url": "https://github.com/websockets/ws/issues" + }, + "bundleDependencies": false, + "dependencies": { + "async-limiter": "~1.0.0" + }, + "deprecated": false, + "description": "Simple to use, blazing fast and thoroughly tested websocket client and server for Node.js", + "devDependencies": { + "benchmark": "~2.1.2", + "bufferutil": "~3.0.0", + "eslint": "~4.18.0", + "eslint-config-standard": "~11.0.0", + "eslint-plugin-import": "~2.9.0", + "eslint-plugin-node": "~6.0.0", + "eslint-plugin-promise": "~3.6.0", + "eslint-plugin-standard": "~3.0.0", + "mocha": "~5.0.0", + "nyc": "~11.4.1", + "utf-8-validate": "~4.0.0" + }, + "files": [ + "index.js", + "lib" + ], + "homepage": "https://github.com/websockets/ws", + "keywords": [ + "HyBi", + "Push", + "RFC-6455", + "WebSocket", + "WebSockets", + "real-time" + ], + "license": "MIT", + "main": "index.js", + "name": "ws", + "repository": { + "type": "git", + "url": "git+https://github.com/websockets/ws.git" + }, + "scripts": { + "integration": "eslint . && mocha test/*.integration.js", + "lint": "eslint .", + "test": "eslint . && nyc --reporter=html --reporter=text mocha test/*.test.js" + }, + "version": "5.0.0" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jscsrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jscsrc new file mode 100644 index 0000000000000000000000000000000000000000..a37d119c4261591c5c01fc61cf2c871fa010b755 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jscsrc @@ -0,0 +1,6 @@ +{ + "preset": "crockford", + "validateIndentation": "\t", + "disallowKeywords": ["with"], + "disallowDanglingUnderscores": null +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jshintrc b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jshintrc new file mode 100644 index 0000000000000000000000000000000000000000..1cca0fab33f000c0e8a8a7c4bc1230d93755cf6c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.jshintrc @@ -0,0 +1,27 @@ +{ + "bitwise": false, + "curly": true, + "eqeqeq": true, + "forin": true, + "freeze": true, + "latedef": "function", + "noarg": true, + "nonbsp": true, + "nonew": true, + "plusplus": false, + "undef": true, + "unused": true, + "strict": false, + "maxparams": 6, + "maxdepth": 4, + "maxstatements": false, + "maxlen": 200, + "browser": true, + "browserify": true, + "devel": true, + "jquery": false, + "mocha": true, + "node": false, + "shelljs": false, + "worker": false +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.npmignore b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.npmignore new file mode 100644 index 0000000000000000000000000000000000000000..2ccbe4656c6078ded72491cf2ee9c5ec20219624 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/.npmignore @@ -0,0 +1 @@ +/node_modules/ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/LICENSE b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..a64a4125c18ba58ffa871adcc338b0a8311a96e7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2015 Iñaki Baz Castillo, <ibc@aliax.net> + +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/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/README.md new file mode 100644 index 0000000000000000000000000000000000000000..db253a4375d5eecdcc4640e1d41db9d9e4ba7ce3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/README.md @@ -0,0 +1,98 @@ +# yaeti + +Yet Another [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) Implementation. + +The library exposes both the [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) interface and the [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface. + + +## Installation + +```bash +$ npm install yaeti --save +``` + + +## Usage + +```javascript +var yaeti = require('yaeti'); + + +// Custom class we want to make an EventTarget. +function Foo() { + // Make Foo an EventTarget. + yaeti.EventTarget.call(this); +} + +// Create an instance. +var foo = new Foo(); + +function listener1() { + console.log('listener1'); +} + +function listener2() { + console.log('listener2'); +} + +foo.addEventListener('bar', listener1); +foo.addEventListener('bar', listener2); +foo.removeEventListener('bar', listener1); + +var event = new yaeti.Event('bar'); + +foo.dispatchEvent(event); + + +// Output: +// => "listener2" +``` + + + +## API + + +#### `yaeti.EventTarget` interface + +Implementation of the [EventTarget](https://developer.mozilla.org/es/docs/Web/API/EventTarget) interface. + +* Make a custom class inherit from `EventTarget`: +```javascript +function Foo() { + yaeti.EventTarget.call(this); +} +``` + +* Make an existing object an `EventTarget`: +```javascript +yaeti.EventTarget.call(obj); +``` + +The interface implements the `addEventListener`, `removeEventListener` and `dispatchEvent` methods as defined by the W3C. + + +##### `listeners` read-only property + +Returns an object whose keys are configured event types (String) and whose values are an array of listeners (functions) for those event types. + + +#### `yaeti.Event` interface + +Implementation of the [Event](https://developer.mozilla.org/en-US/docs/Web/API/Event) interface. + +*NOTE:* Just useful in Node (the browser already exposes the native `Event` interface). + +```javascript +var event = new yaeti.Event('bar'); +``` + + +## Author + +[Iñaki Baz Castillo](https://github.com/ibc) + + +## License + +[MIT](./LICENSE) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/gulpfile.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/gulpfile.js new file mode 100644 index 0000000000000000000000000000000000000000..294cd9c7c05a3cd10c1e19bf0a97611eb6202f55 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/gulpfile.js @@ -0,0 +1,23 @@ +var + /** + * Dependencies. + */ + gulp = require('gulp'), + jscs = require('gulp-jscs'), + jshint = require('gulp-jshint'), + stylish = require('gulp-jscs-stylish'); + + +gulp.task('lint', function () { + var src = ['gulpfile.js', 'index.js', 'lib/**/*.js']; + + return gulp.src(src) + .pipe(jshint('.jshintrc')) // Enforce good practics. + .pipe(jscs('.jscsrc')) // Enforce style guide. + .pipe(stylish.combineWithHintResults()) + .pipe(jshint.reporter('jshint-stylish', {verbose: true})) + .pipe(jshint.reporter('fail')); +}); + + +gulp.task('default', gulp.task('lint')); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/index.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/index.js new file mode 100644 index 0000000000000000000000000000000000000000..b1e6db47e276e09ae1c0b8cbb2ba0357628b3cb7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/index.js @@ -0,0 +1,4 @@ +module.exports = { + EventTarget : require('./lib/EventTarget'), + Event : require('./lib/Event') +}; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.browser.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.browser.js new file mode 100644 index 0000000000000000000000000000000000000000..0cd5ea68aeb0f9962991a6cc4659af7a6bfceab7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.browser.js @@ -0,0 +1,5 @@ +/** + * In browsers export the native Event interface. + */ + +module.exports = global.Event; diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.js new file mode 100644 index 0000000000000000000000000000000000000000..cd245a27a46f7fc0f8f7805dc9124d5e089cbf58 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/Event.js @@ -0,0 +1,13 @@ +/** + * Expose the Event class. + */ +module.exports = _Event; + + +function _Event(type) { + this.type = type; + this.isTrusted = false; + + // Set a flag indicating this is not a DOM Event object + this._yaeti = true; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/EventTarget.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/EventTarget.js new file mode 100644 index 0000000000000000000000000000000000000000..403c75bd4e3a6b6dff6ba8a865d3b6292793f985 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/lib/EventTarget.js @@ -0,0 +1,119 @@ +/** + * Expose the _EventTarget class. + */ +module.exports = _EventTarget; + +function _EventTarget() { + // Do nothing if called for a native EventTarget object.. + if (typeof this.addEventListener === 'function') { + return; + } + + this._listeners = {}; + + this.addEventListener = _addEventListener; + this.removeEventListener = _removeEventListener; + this.dispatchEvent = _dispatchEvent; +} + +Object.defineProperties(_EventTarget.prototype, { + listeners: { + get: function () { + return this._listeners; + } + } +}); + +function _addEventListener(type, newListener) { + var + listenersType, + i, listener; + + if (!type || !newListener) { + return; + } + + listenersType = this._listeners[type]; + if (listenersType === undefined) { + this._listeners[type] = listenersType = []; + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (listener === newListener) { + return; + } + } + + listenersType.push(newListener); +} + +function _removeEventListener(type, oldListener) { + var + listenersType, + i, listener; + + if (!type || !oldListener) { + return; + } + + listenersType = this._listeners[type]; + if (listenersType === undefined) { + return; + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (listener === oldListener) { + listenersType.splice(i, 1); + break; + } + } + + if (listenersType.length === 0) { + delete this._listeners[type]; + } +} + +function _dispatchEvent(event) { + var + type, + listenersType, + dummyListener, + stopImmediatePropagation = false, + i, listener; + + if (!event || typeof event.type !== 'string') { + throw new Error('`event` must have a valid `type` property'); + } + + // Do some stuff to emulate DOM Event behavior (just if this is not a + // DOM Event object) + if (event._yaeti) { + event.target = this; + event.cancelable = true; + } + + // Attempt to override the stopImmediatePropagation() method + try { + event.stopImmediatePropagation = function () { + stopImmediatePropagation = true; + }; + } catch (error) {} + + type = event.type; + listenersType = (this._listeners[type] || []); + + dummyListener = this['on' + type]; + if (typeof dummyListener === 'function') { + dummyListener.call(this, event); + } + + for (i = 0; !!(listener = listenersType[i]); i++) { + if (stopImmediatePropagation) { + break; + } + + listener.call(this, event); + } + + return !event.defaultPrevented; +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/package.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/package.json new file mode 100644 index 0000000000000000000000000000000000000000..abbbda20c0a452c4f4eca2cd09342f16596d281d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/node_modules/yaeti/package.json @@ -0,0 +1,57 @@ +{ + "_from": "yaeti@^0.0.6", + "_id": "yaeti@0.0.6", + "_inBundle": false, + "_integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=", + "_location": "/yaeti", + "_phantomChildren": {}, + "_requested": { + "type": "range", + "registry": true, + "raw": "yaeti@^0.0.6", + "name": "yaeti", + "escapedName": "yaeti", + "rawSpec": "^0.0.6", + "saveSpec": null, + "fetchSpec": "^0.0.6" + }, + "_requiredBy": [ + "/websocket" + ], + "_resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "_shasum": "f26f484d72684cf42bedfb76970aa1608fbf9577", + "_spec": "yaeti@^0.0.6", + "_where": "/Users/Kens/Desktop/NPS Schoolwork/MV3500 Networks/Final Project/scripts/node_modules/websocket", + "author": { + "name": "Iñaki Baz Castillo", + "email": "ibc@aliax.net" + }, + "browser": { + "./lib/Event.js": "./lib/Event.browser.js" + }, + "bugs": { + "url": "https://github.com/ibc/yaeti/issues" + }, + "bundleDependencies": false, + "deprecated": false, + "description": "Yet Another EventTarget Implementation", + "devDependencies": { + "gulp": "git+https://github.com/gulpjs/gulp.git#4.0", + "gulp-jscs": "^1.6.0", + "gulp-jscs-stylish": "^1.1.0", + "gulp-jshint": "^1.11.2", + "jshint-stylish": "~1.0.2" + }, + "engines": { + "node": ">=0.10.32" + }, + "homepage": "https://github.com/ibc/yaeti#readme", + "license": "MIT", + "main": "index.js", + "name": "yaeti", + "repository": { + "type": "git", + "url": "git+https://github.com/ibc/yaeti.git" + }, + "version": "0.0.6" +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/package-lock.json b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..601d07db72e60296809fc1390c539f0180efef89 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/package-lock.json @@ -0,0 +1,66 @@ +{ + "requires": true, + "lockfileVersion": 1, + "dependencies": { + "async-limiter": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/async-limiter/-/async-limiter-1.0.0.tgz", + "integrity": "sha512-jp/uFnooOiO+L211eZOoSyzpOITMXx1rBITauYykG3BRYPu8h0UcxsPNB04RR5vo4Tyz3+ay17tR6JVf9qzYWg==" + }, + "debug": { + "version": "2.6.9", + "resolved": "https://registry.npmjs.org/debug/-/debug-2.6.9.tgz", + "integrity": "sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA==", + "requires": { + "ms": "2.0.0" + } + }, + "is-typedarray": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/is-typedarray/-/is-typedarray-1.0.0.tgz", + "integrity": "sha1-5HnICFjfDBsR3dppQPlgEfzaSpo=" + }, + "ms": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.0.0.tgz", + "integrity": "sha1-VgiurfwAvmwpAd9fmGF4jeDVl8g=" + }, + "nan": { + "version": "2.10.0", + "resolved": "https://registry.npmjs.org/nan/-/nan-2.10.0.tgz", + "integrity": "sha512-bAdJv7fBLhWC+/Bls0Oza+mvTaNQtP+1RyhhhvD95pgUJz6XM5IzgmxOkItJ9tkoCiplvAnXI1tNmmUD/eScyA==" + }, + "typedarray-to-buffer": { + "version": "3.1.5", + "resolved": "https://registry.npmjs.org/typedarray-to-buffer/-/typedarray-to-buffer-3.1.5.tgz", + "integrity": "sha512-zdu8XMNEDepKKR+XYOXAVPtWui0ly0NtohUscw+UmaHiAWT8hrV1rr//H6V+0DvJ3OQ19S979M0laLfX8rm82Q==", + "requires": { + "is-typedarray": "1.0.0" + } + }, + "websocket": { + "version": "1.0.25", + "resolved": "https://registry.npmjs.org/websocket/-/websocket-1.0.25.tgz", + "integrity": "sha512-M58njvi6ZxVb5k7kpnHh2BvNKuBWiwIYvsToErBzWhvBZYwlEiLcyLrG41T1jRcrY9ettqPYEqduLI7ul54CVQ==", + "requires": { + "debug": "2.6.9", + "nan": "2.10.0", + "typedarray-to-buffer": "3.1.5", + "yaeti": "0.0.6" + } + }, + "ws": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/ws/-/ws-5.0.0.tgz", + "integrity": "sha512-XXG4S0b771C68AeTHebBsJJBZMguxj7Em+D657RViuj6ppRd3tfuOhIK8eGwZGNb76C8MjQfCTfH2NN50rJN4w==", + "requires": { + "async-limiter": "1.0.0" + } + }, + "yaeti": { + "version": "0.0.6", + "resolved": "https://registry.npmjs.org/yaeti/-/yaeti-0.0.6.tgz", + "integrity": "sha1-8m9ITXJoTPQr7ft2lwqhYI+/lXc=" + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/r.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/r.js new file mode 100644 index 0000000000000000000000000000000000000000..d8c8dc4bf59f9463821d7951f1becc27c7c724b4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/r.js @@ -0,0 +1,30419 @@ +/** + * @license r.js 2.3.5 Copyright jQuery Foundation and other contributors. + * Released under MIT license, http://github.com/requirejs/r.js/LICENSE + */ + +/* + * This is a bootstrap script to allow running RequireJS in the command line + * in either a Java/Rhino or Node environment. It is modified by the top-level + * dist.js file to inject other files to completely enable this file. It is + * the shell of the r.js file. + */ + +/*jslint evil: true, nomen: true, sloppy: true */ +/*global readFile: true, process: false, Packages: false, print: false, +console: false, java: false, module: false, requirejsVars, navigator, +document, importScripts, self, location, Components, FileUtils */ + +var requirejs, require, define, xpcUtil; +(function (console, args, readFileFunc) { + var fileName, env, fs, vm, path, exec, rhinoContext, dir, nodeRequire, + nodeDefine, exists, reqMain, loadedOptimizedLib, existsForNode, Cc, Ci, + version = '2.3.5', + jsSuffixRegExp = /\.js$/, + commandOption = '', + useLibLoaded = {}, + //Used by jslib/rhino/args.js + rhinoArgs = args, + //Used by jslib/xpconnect/args.js + xpconnectArgs = args, + readFile = typeof readFileFunc !== 'undefined' ? readFileFunc : null; + + function showHelp() { + console.log('See https://github.com/requirejs/r.js for usage.'); + } + + if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { + env = 'node'; + + //Get the fs module via Node's require before it + //gets replaced. Used in require/node.js + fs = require('fs'); + vm = require('vm'); + path = require('path'); + //In Node 0.7+ existsSync is on fs. + existsForNode = fs.existsSync || path.existsSync; + + nodeRequire = require; + nodeDefine = define; + reqMain = require.main; + + //Temporarily hide require and define to allow require.js to define + //them. + require = undefined; + define = undefined; + + readFile = function (path) { + return fs.readFileSync(path, 'utf8'); + }; + + exec = function (string, name) { + return vm.runInThisContext(this.requirejsVars.require.makeNodeWrapper(string), + name ? fs.realpathSync(name) : ''); + }; + + exists = function (fileName) { + return existsForNode(fileName); + }; + + + fileName = process.argv[2]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = process.argv[3]; + } + } else if (typeof Packages !== 'undefined') { + env = 'rhino'; + + fileName = args[0]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = args[1]; + } + + //Exec/readFile differs between Rhino and Nashorn. Rhino has an + //importPackage where Nashorn does not, so branch on that. This is a + //coarser check -- detecting readFile existence might also be enough for + //this spot. However, sticking with importPackage to keep it the same + //as other Rhino/Nashorn detection branches. + if (typeof importPackage !== 'undefined') { + rhinoContext = Packages.org.mozilla.javascript.ContextFactory.getGlobal().enterContext(); + + exec = function (string, name) { + return rhinoContext.evaluateString(this, string, name, 0, null); + }; + } else { + exec = function (string, name) { + load({ script: string, name: name}); + }; + readFile = readFully; + } + + exists = function (fileName) { + return (new java.io.File(fileName)).exists(); + }; + + //Define a console.log for easier logging. Don't + //get fancy though. + if (typeof console === 'undefined') { + console = { + log: function () { + print.apply(undefined, arguments); + } + }; + } + } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || + (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { + env = 'browser'; + + readFile = function (path) { + return fs.readFileSync(path, 'utf8'); + }; + + exec = function (string) { + return eval(string); + }; + + exists = function () { + console.log('x.js exists not applicable in browser env'); + return false; + }; + + } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { + env = 'xpconnect'; + + Components.utils['import']('resource://gre/modules/FileUtils.jsm'); + Cc = Components.classes; + Ci = Components.interfaces; + + fileName = args[0]; + + if (fileName && fileName.indexOf('-') === 0) { + commandOption = fileName.substring(1); + fileName = args[1]; + } + + xpcUtil = { + isWindows: ('@mozilla.org/windows-registry-key;1' in Cc), + cwd: function () { + return FileUtils.getFile("CurWorkD", []).path; + }, + + //Remove . and .. from paths, normalize on front slashes + normalize: function (path) { + //There has to be an easier way to do this. + var i, part, ary, + firstChar = path.charAt(0); + + if (firstChar !== '/' && + firstChar !== '\\' && + path.indexOf(':') === -1) { + //A relative path. Use the current working directory. + path = xpcUtil.cwd() + '/' + path; + } + + ary = path.replace(/\\/g, '/').split('/'); + + for (i = 0; i < ary.length; i += 1) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + ary.splice(i - 1, 2); + i -= 2; + } + } + return ary.join('/'); + }, + + xpfile: function (path) { + var fullPath; + try { + fullPath = xpcUtil.normalize(path); + if (xpcUtil.isWindows) { + fullPath = fullPath.replace(/\//g, '\\'); + } + return new FileUtils.File(fullPath); + } catch (e) { + throw new Error((fullPath || path) + ' failed: ' + e); + } + }, + + readFile: function (/*String*/path, /*String?*/encoding) { + //A file read function that can deal with BOMs + encoding = encoding || "utf-8"; + + var inStream, convertStream, + readData = {}, + fileObj = xpcUtil.xpfile(path); + + //XPCOM, you so crazy + try { + inStream = Cc['@mozilla.org/network/file-input-stream;1'] + .createInstance(Ci.nsIFileInputStream); + inStream.init(fileObj, 1, 0, false); + + convertStream = Cc['@mozilla.org/intl/converter-input-stream;1'] + .createInstance(Ci.nsIConverterInputStream); + convertStream.init(inStream, encoding, inStream.available(), + Ci.nsIConverterInputStream.DEFAULT_REPLACEMENT_CHARACTER); + + convertStream.readString(inStream.available(), readData); + return readData.value; + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } finally { + if (convertStream) { + convertStream.close(); + } + if (inStream) { + inStream.close(); + } + } + } + }; + + readFile = xpcUtil.readFile; + + exec = function (string) { + return eval(string); + }; + + exists = function (fileName) { + return xpcUtil.xpfile(fileName).exists(); + }; + + //Define a console.log for easier logging. Don't + //get fancy though. + if (typeof console === 'undefined') { + console = { + log: function () { + print.apply(undefined, arguments); + } + }; + } + } + + /** vim: et:ts=4:sw=4:sts=4 + * @license RequireJS 2.3.5 Copyright jQuery Foundation and other contributors. + * Released under MIT license, https://github.com/requirejs/requirejs/blob/master/LICENSE + */ +//Not using strict: uneven strict support in browsers, #392, and causes +//problems with requirejs.exec()/transpiler plugins that may not be strict. +/*jslint regexp: true, nomen: true, sloppy: true */ +/*global window, navigator, document, importScripts, setTimeout, opera */ + + +(function (global, setTimeout) { + var req, s, head, baseElement, dataMain, src, + interactiveScript, currentlyAddingScript, mainScript, subPath, + version = '2.3.5', + commentRegExp = /\/\*[\s\S]*?\*\/|([^:"'=]|^)\/\/.*$/mg, + cjsRequireRegExp = /[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, + jsSuffixRegExp = /\.js$/, + currDirRegExp = /^\.\//, + op = Object.prototype, + ostring = op.toString, + hasOwn = op.hasOwnProperty, + isBrowser = !!(typeof window !== 'undefined' && typeof navigator !== 'undefined' && window.document), + isWebWorker = !isBrowser && typeof importScripts !== 'undefined', + //PS3 indicates loaded and complete, but need to wait for complete + //specifically. Sequence is 'loading', 'loaded', execution, + // then 'complete'. The UA check is unfortunate, but not sure how + //to feature test w/o causing perf issues. + readyRegExp = isBrowser && navigator.platform === 'PLAYSTATION 3' ? + /^complete$/ : /^(complete|loaded)$/, + defContextName = '_', + //Oh the tragedy, detecting opera. See the usage of isOpera for reason. + isOpera = typeof opera !== 'undefined' && opera.toString() === '[object Opera]', + contexts = {}, + cfg = {}, + globalDefQueue = [], + useInteractive = false; + + //Could match something like ')//comment', do not lose the prefix to comment. + function commentReplace(match, singlePrefix) { + return singlePrefix || ''; + } + + function isFunction(it) { + return ostring.call(it) === '[object Function]'; + } + + function isArray(it) { + return ostring.call(it) === '[object Array]'; + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + /** + * Helper function for iterating over an array backwards. If the func + * returns a true value, it will break out of the loop. + */ + function eachReverse(ary, func) { + if (ary) { + var i; + for (i = ary.length - 1; i > -1; i -= 1) { + if (ary[i] && func(ary[i], i, ary)) { + break; + } + } + } + } + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function getOwn(obj, prop) { + return hasProp(obj, prop) && obj[prop]; + } + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + } + + /** + * Simple function to mix in properties from source into target, + * but only if target does not already have a property of the same name. + */ + function mixin(target, source, force, deepStringMixin) { + if (source) { + eachProp(source, function (value, prop) { + if (force || !hasProp(target, prop)) { + if (deepStringMixin && typeof value === 'object' && value && + !isArray(value) && !isFunction(value) && + !(value instanceof RegExp)) { + + if (!target[prop]) { + target[prop] = {}; + } + mixin(target[prop], value, force, deepStringMixin); + } else { + target[prop] = value; + } + } + }); + } + return target; + } + + //Similar to Function.prototype.bind, but the 'this' object is specified + //first, since it is easier to read/figure out what 'this' will be. + function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + } + + function scripts() { + return document.getElementsByTagName('script'); + } + + function defaultOnError(err) { + throw err; + } + + //Allow getting a global that is expressed in + //dot notation, like 'a.b.c'. + function getGlobal(value) { + if (!value) { + return value; + } + var g = global; + each(value.split('.'), function (part) { + g = g[part]; + }); + return g; + } + + /** + * Constructs an error with a pointer to an URL with more information. + * @param {String} id the error ID that maps to an ID on a web page. + * @param {String} message human readable error. + * @param {Error} [err] the original error, if there is one. + * + * @returns {Error} + */ + function makeError(id, msg, err, requireModules) { + var e = new Error(msg + '\nhttp://requirejs.org/docs/errors.html#' + id); + e.requireType = id; + e.requireModules = requireModules; + if (err) { + e.originalError = err; + } + return e; + } + + if (typeof define !== 'undefined') { + //If a define is already in play via another AMD loader, + //do not overwrite. + return; + } + + if (typeof requirejs !== 'undefined') { + if (isFunction(requirejs)) { + //Do not overwrite an existing requirejs instance. + return; + } + cfg = requirejs; + requirejs = undefined; + } + + //Allow for a require config object + if (typeof require !== 'undefined' && !isFunction(require)) { + //assume it is a config object. + cfg = require; + require = undefined; + } + + function newContext(contextName) { + var inCheckLoaded, Module, context, handlers, + checkLoadedTimeoutId, + config = { + //Defaults. Do not set a default for map + //config to speed up normalize(), which + //will run faster if there is no default. + waitSeconds: 7, + baseUrl: './', + paths: {}, + bundles: {}, + pkgs: {}, + shim: {}, + config: {} + }, + registry = {}, + //registry of just enabled modules, to speed + //cycle breaking code when lots of modules + //are registered, but not activated. + enabledRegistry = {}, + undefEvents = {}, + defQueue = [], + defined = {}, + urlFetched = {}, + bundlesMap = {}, + requireCounter = 1, + unnormalizedCounter = 1; + + /** + * Trims the . and .. from an array of path segments. + * It will keep a leading path segment if a .. will become + * the first path segment, to help with module name lookups, + * which act like paths, but can be remapped. But the end result, + * all paths that use this function should look normalized. + * NOTE: this method MODIFIES the input array. + * @param {Array} ary the array of path segments. + */ + function trimDots(ary) { + var i, part; + for (i = 0; i < ary.length; i++) { + part = ary[i]; + if (part === '.') { + ary.splice(i, 1); + i -= 1; + } else if (part === '..') { + // If at the start, or previous value is still .., + // keep them so that when converted to a path it may + // still work when converted to a path, even though + // as an ID it is less than ideal. In larger point + // releases, may be better to just kick out an error. + if (i === 0 || (i === 1 && ary[2] === '..') || ary[i - 1] === '..') { + continue; + } else if (i > 0) { + ary.splice(i - 1, 2); + i -= 2; + } + } + } + } + + /** + * Given a relative module name, like ./something, normalize it to + * a real name that can be mapped to a path. + * @param {String} name the relative name + * @param {String} baseName a real name that the name arg is relative + * to. + * @param {Boolean} applyMap apply the map config to the value. Should + * only be done if this normalization is for a dependency ID. + * @returns {String} normalized name + */ + function normalize(name, baseName, applyMap) { + var pkgMain, mapValue, nameParts, i, j, nameSegment, lastIndex, + foundMap, foundI, foundStarMap, starI, normalizedBaseParts, + baseParts = (baseName && baseName.split('/')), + map = config.map, + starMap = map && map['*']; + + //Adjust any relative paths. + if (name) { + name = name.split('/'); + lastIndex = name.length - 1; + + // If wanting node ID compatibility, strip .js from end + // of IDs. Have to do this here, and not in nameToUrl + // because node allows either .js or non .js to map + // to same file. + if (config.nodeIdCompat && jsSuffixRegExp.test(name[lastIndex])) { + name[lastIndex] = name[lastIndex].replace(jsSuffixRegExp, ''); + } + + // Starts with a '.' so need the baseName + if (name[0].charAt(0) === '.' && baseParts) { + //Convert baseName to array, and lop off the last part, + //so that . matches that 'directory' and not name of the baseName's + //module. For instance, baseName of 'one/two/three', maps to + //'one/two/three.js', but we want the directory, 'one/two' for + //this normalization. + normalizedBaseParts = baseParts.slice(0, baseParts.length - 1); + name = normalizedBaseParts.concat(name); + } + + trimDots(name); + name = name.join('/'); + } + + //Apply map config if available. + if (applyMap && map && (baseParts || starMap)) { + nameParts = name.split('/'); + + outerLoop: for (i = nameParts.length; i > 0; i -= 1) { + nameSegment = nameParts.slice(0, i).join('/'); + + if (baseParts) { + //Find the longest baseName segment match in the config. + //So, do joins on the biggest to smallest lengths of baseParts. + for (j = baseParts.length; j > 0; j -= 1) { + mapValue = getOwn(map, baseParts.slice(0, j).join('/')); + + //baseName segment has config, find if it has one for + //this name. + if (mapValue) { + mapValue = getOwn(mapValue, nameSegment); + if (mapValue) { + //Match, update name to the new value. + foundMap = mapValue; + foundI = i; + break outerLoop; + } + } + } + } + + //Check for a star map match, but just hold on to it, + //if there is a shorter segment match later in a matching + //config, then favor over this star map. + if (!foundStarMap && starMap && getOwn(starMap, nameSegment)) { + foundStarMap = getOwn(starMap, nameSegment); + starI = i; + } + } + + if (!foundMap && foundStarMap) { + foundMap = foundStarMap; + foundI = starI; + } + + if (foundMap) { + nameParts.splice(0, foundI, foundMap); + name = nameParts.join('/'); + } + } + + // If the name points to a package's name, use + // the package main instead. + pkgMain = getOwn(config.pkgs, name); + + return pkgMain ? pkgMain : name; + } + + function removeScript(name) { + if (isBrowser) { + each(scripts(), function (scriptNode) { + if (scriptNode.getAttribute('data-requiremodule') === name && + scriptNode.getAttribute('data-requirecontext') === context.contextName) { + scriptNode.parentNode.removeChild(scriptNode); + return true; + } + }); + } + } + + function hasPathFallback(id) { + var pathConfig = getOwn(config.paths, id); + if (pathConfig && isArray(pathConfig) && pathConfig.length > 1) { + //Pop off the first array value, since it failed, and + //retry + pathConfig.shift(); + context.require.undef(id); + + //Custom require that does not do map translation, since + //ID is "absolute", already mapped/resolved. + context.makeRequire(null, { + skipMap: true + })([id]); + + return true; + } + } + + //Turns a plugin!resource to [plugin, resource] + //with the plugin being undefined if the name + //did not have a plugin prefix. + function splitPrefix(name) { + var prefix, + index = name ? name.indexOf('!') : -1; + if (index > -1) { + prefix = name.substring(0, index); + name = name.substring(index + 1, name.length); + } + return [prefix, name]; + } + + /** + * Creates a module mapping that includes plugin prefix, module + * name, and path. If parentModuleMap is provided it will + * also normalize the name via require.normalize() + * + * @param {String} name the module name + * @param {String} [parentModuleMap] parent module map + * for the module name, used to resolve relative names. + * @param {Boolean} isNormalized: is the ID already normalized. + * This is true if this call is done for a define() module ID. + * @param {Boolean} applyMap: apply the map config to the ID. + * Should only be true if this map is for a dependency. + * + * @returns {Object} + */ + function makeModuleMap(name, parentModuleMap, isNormalized, applyMap) { + var url, pluginModule, suffix, nameParts, + prefix = null, + parentName = parentModuleMap ? parentModuleMap.name : null, + originalName = name, + isDefine = true, + normalizedName = ''; + + //If no name, then it means it is a require call, generate an + //internal name. + if (!name) { + isDefine = false; + name = '_@r' + (requireCounter += 1); + } + + nameParts = splitPrefix(name); + prefix = nameParts[0]; + name = nameParts[1]; + + if (prefix) { + prefix = normalize(prefix, parentName, applyMap); + pluginModule = getOwn(defined, prefix); + } + + //Account for relative paths if there is a base name. + if (name) { + if (prefix) { + if (isNormalized) { + normalizedName = name; + } else if (pluginModule && pluginModule.normalize) { + //Plugin is loaded, use its normalize method. + normalizedName = pluginModule.normalize(name, function (name) { + return normalize(name, parentName, applyMap); + }); + } else { + // If nested plugin references, then do not try to + // normalize, as it will not normalize correctly. This + // places a restriction on resourceIds, and the longer + // term solution is not to normalize until plugins are + // loaded and all normalizations to allow for async + // loading of a loader plugin. But for now, fixes the + // common uses. Details in #1131 + normalizedName = name.indexOf('!') === -1 ? + normalize(name, parentName, applyMap) : + name; + } + } else { + //A regular module. + normalizedName = normalize(name, parentName, applyMap); + + //Normalized name may be a plugin ID due to map config + //application in normalize. The map config values must + //already be normalized, so do not need to redo that part. + nameParts = splitPrefix(normalizedName); + prefix = nameParts[0]; + normalizedName = nameParts[1]; + isNormalized = true; + + url = context.nameToUrl(normalizedName); + } + } + + //If the id is a plugin id that cannot be determined if it needs + //normalization, stamp it with a unique ID so two matching relative + //ids that may conflict can be separate. + suffix = prefix && !pluginModule && !isNormalized ? + '_unnormalized' + (unnormalizedCounter += 1) : + ''; + + return { + prefix: prefix, + name: normalizedName, + parentMap: parentModuleMap, + unnormalized: !!suffix, + url: url, + originalName: originalName, + isDefine: isDefine, + id: (prefix ? + prefix + '!' + normalizedName : + normalizedName) + suffix + }; + } + + function getModule(depMap) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (!mod) { + mod = registry[id] = new context.Module(depMap); + } + + return mod; + } + + function on(depMap, name, fn) { + var id = depMap.id, + mod = getOwn(registry, id); + + if (hasProp(defined, id) && + (!mod || mod.defineEmitComplete)) { + if (name === 'defined') { + fn(defined[id]); + } + } else { + mod = getModule(depMap); + if (mod.error && name === 'error') { + fn(mod.error); + } else { + mod.on(name, fn); + } + } + } + + function onError(err, errback) { + var ids = err.requireModules, + notified = false; + + if (errback) { + errback(err); + } else { + each(ids, function (id) { + var mod = getOwn(registry, id); + if (mod) { + //Set error on module, so it skips timeout checks. + mod.error = err; + if (mod.events.error) { + notified = true; + mod.emit('error', err); + } + } + }); + + if (!notified) { + req.onError(err); + } + } + } + + /** + * Internal method to transfer globalQueue items to this context's + * defQueue. + */ + function takeGlobalQueue() { + //Push all the globalDefQueue items into the context's defQueue + if (globalDefQueue.length) { + each(globalDefQueue, function(queueItem) { + var id = queueItem[0]; + if (typeof id === 'string') { + context.defQueueMap[id] = true; + } + defQueue.push(queueItem); + }); + globalDefQueue = []; + } + } + + handlers = { + 'require': function (mod) { + if (mod.require) { + return mod.require; + } else { + return (mod.require = context.makeRequire(mod.map)); + } + }, + 'exports': function (mod) { + mod.usingExports = true; + if (mod.map.isDefine) { + if (mod.exports) { + return (defined[mod.map.id] = mod.exports); + } else { + return (mod.exports = defined[mod.map.id] = {}); + } + } + }, + 'module': function (mod) { + if (mod.module) { + return mod.module; + } else { + return (mod.module = { + id: mod.map.id, + uri: mod.map.url, + config: function () { + return getOwn(config.config, mod.map.id) || {}; + }, + exports: mod.exports || (mod.exports = {}) + }); + } + } + }; + + function cleanRegistry(id) { + //Clean up machinery used for waiting modules. + delete registry[id]; + delete enabledRegistry[id]; + } + + function breakCycle(mod, traced, processed) { + var id = mod.map.id; + + if (mod.error) { + mod.emit('error', mod.error); + } else { + traced[id] = true; + each(mod.depMaps, function (depMap, i) { + var depId = depMap.id, + dep = getOwn(registry, depId); + + //Only force things that have not completed + //being defined, so still in the registry, + //and only if it has not been matched up + //in the module already. + if (dep && !mod.depMatched[i] && !processed[depId]) { + if (getOwn(traced, depId)) { + mod.defineDep(i, defined[depId]); + mod.check(); //pass false? + } else { + breakCycle(dep, traced, processed); + } + } + }); + processed[id] = true; + } + } + + function checkLoaded() { + var err, usingPathFallback, + waitInterval = config.waitSeconds * 1000, + //It is possible to disable the wait interval by using waitSeconds of 0. + expired = waitInterval && (context.startTime + waitInterval) < new Date().getTime(), + noLoads = [], + reqCalls = [], + stillLoading = false, + needCycleCheck = true; + + //Do not bother if this call was a result of a cycle break. + if (inCheckLoaded) { + return; + } + + inCheckLoaded = true; + + //Figure out the state of all the modules. + eachProp(enabledRegistry, function (mod) { + var map = mod.map, + modId = map.id; + + //Skip things that are not enabled or in error state. + if (!mod.enabled) { + return; + } + + if (!map.isDefine) { + reqCalls.push(mod); + } + + if (!mod.error) { + //If the module should be executed, and it has not + //been inited and time is up, remember it. + if (!mod.inited && expired) { + if (hasPathFallback(modId)) { + usingPathFallback = true; + stillLoading = true; + } else { + noLoads.push(modId); + removeScript(modId); + } + } else if (!mod.inited && mod.fetched && map.isDefine) { + stillLoading = true; + if (!map.prefix) { + //No reason to keep looking for unfinished + //loading. If the only stillLoading is a + //plugin resource though, keep going, + //because it may be that a plugin resource + //is waiting on a non-plugin cycle. + return (needCycleCheck = false); + } + } + } + }); + + if (expired && noLoads.length) { + //If wait time expired, throw error of unloaded modules. + err = makeError('timeout', 'Load timeout for modules: ' + noLoads, null, noLoads); + err.contextName = context.contextName; + return onError(err); + } + + //Not expired, check for a cycle. + if (needCycleCheck) { + each(reqCalls, function (mod) { + breakCycle(mod, {}, {}); + }); + } + + //If still waiting on loads, and the waiting load is something + //other than a plugin resource, or there are still outstanding + //scripts, then just try back later. + if ((!expired || usingPathFallback) && stillLoading) { + //Something is still waiting to load. Wait for it, but only + //if a timeout is not already in effect. + if ((isBrowser || isWebWorker) && !checkLoadedTimeoutId) { + checkLoadedTimeoutId = setTimeout(function () { + checkLoadedTimeoutId = 0; + checkLoaded(); + }, 50); + } + } + + inCheckLoaded = false; + } + + Module = function (map) { + this.events = getOwn(undefEvents, map.id) || {}; + this.map = map; + this.shim = getOwn(config.shim, map.id); + this.depExports = []; + this.depMaps = []; + this.depMatched = []; + this.pluginMaps = {}; + this.depCount = 0; + + /* this.exports this.factory + this.depMaps = [], + this.enabled, this.fetched + */ + }; + + Module.prototype = { + init: function (depMaps, factory, errback, options) { + options = options || {}; + + //Do not do more inits if already done. Can happen if there + //are multiple define calls for the same module. That is not + //a normal, common case, but it is also not unexpected. + if (this.inited) { + return; + } + + this.factory = factory; + + if (errback) { + //Register for errors on this module. + this.on('error', errback); + } else if (this.events.error) { + //If no errback already, but there are error listeners + //on this module, set up an errback to pass to the deps. + errback = bind(this, function (err) { + this.emit('error', err); + }); + } + + //Do a copy of the dependency array, so that + //source inputs are not modified. For example + //"shim" deps are passed in here directly, and + //doing a direct modification of the depMaps array + //would affect that config. + this.depMaps = depMaps && depMaps.slice(0); + + this.errback = errback; + + //Indicate this module has be initialized + this.inited = true; + + this.ignore = options.ignore; + + //Could have option to init this module in enabled mode, + //or could have been previously marked as enabled. However, + //the dependencies are not known until init is called. So + //if enabled previously, now trigger dependencies as enabled. + if (options.enabled || this.enabled) { + //Enable this module and dependencies. + //Will call this.check() + this.enable(); + } else { + this.check(); + } + }, + + defineDep: function (i, depExports) { + //Because of cycles, defined callback for a given + //export can be called more than once. + if (!this.depMatched[i]) { + this.depMatched[i] = true; + this.depCount -= 1; + this.depExports[i] = depExports; + } + }, + + fetch: function () { + if (this.fetched) { + return; + } + this.fetched = true; + + context.startTime = (new Date()).getTime(); + + var map = this.map; + + //If the manager is for a plugin managed resource, + //ask the plugin to load it now. + if (this.shim) { + context.makeRequire(this.map, { + enableBuildCallback: true + })(this.shim.deps || [], bind(this, function () { + return map.prefix ? this.callPlugin() : this.load(); + })); + } else { + //Regular dependency. + return map.prefix ? this.callPlugin() : this.load(); + } + }, + + load: function () { + var url = this.map.url; + + //Regular dependency. + if (!urlFetched[url]) { + urlFetched[url] = true; + context.load(this.map.id, url); + } + }, + + /** + * Checks if the module is ready to define itself, and if so, + * define it. + */ + check: function () { + if (!this.enabled || this.enabling) { + return; + } + + var err, cjsModule, + id = this.map.id, + depExports = this.depExports, + exports = this.exports, + factory = this.factory; + + if (!this.inited) { + // Only fetch if not already in the defQueue. + if (!hasProp(context.defQueueMap, id)) { + this.fetch(); + } + } else if (this.error) { + this.emit('error', this.error); + } else if (!this.defining) { + //The factory could trigger another require call + //that would result in checking this module to + //define itself again. If already in the process + //of doing that, skip this work. + this.defining = true; + + if (this.depCount < 1 && !this.defined) { + if (isFunction(factory)) { + //If there is an error listener, favor passing + //to that instead of throwing an error. However, + //only do it for define()'d modules. require + //errbacks should not be called for failures in + //their callbacks (#699). However if a global + //onError is set, use that. + if ((this.events.error && this.map.isDefine) || + req.onError !== defaultOnError) { + try { + exports = context.execCb(id, factory, depExports, exports); + } catch (e) { + err = e; + } + } else { + exports = context.execCb(id, factory, depExports, exports); + } + + // Favor return value over exports. If node/cjs in play, + // then will not have a return value anyway. Favor + // module.exports assignment over exports object. + if (this.map.isDefine && exports === undefined) { + cjsModule = this.module; + if (cjsModule) { + exports = cjsModule.exports; + } else if (this.usingExports) { + //exports already set the defined value. + exports = this.exports; + } + } + + if (err) { + err.requireMap = this.map; + err.requireModules = this.map.isDefine ? [this.map.id] : null; + err.requireType = this.map.isDefine ? 'define' : 'require'; + return onError((this.error = err)); + } + + } else { + //Just a literal value + exports = factory; + } + + this.exports = exports; + + if (this.map.isDefine && !this.ignore) { + defined[id] = exports; + + if (req.onResourceLoad) { + var resLoadMaps = []; + each(this.depMaps, function (depMap) { + resLoadMaps.push(depMap.normalizedMap || depMap); + }); + req.onResourceLoad(context, this.map, resLoadMaps); + } + } + + //Clean up + cleanRegistry(id); + + this.defined = true; + } + + //Finished the define stage. Allow calling check again + //to allow define notifications below in the case of a + //cycle. + this.defining = false; + + if (this.defined && !this.defineEmitted) { + this.defineEmitted = true; + this.emit('defined', this.exports); + this.defineEmitComplete = true; + } + + } + }, + + callPlugin: function () { + var map = this.map, + id = map.id, + //Map already normalized the prefix. + pluginMap = makeModuleMap(map.prefix); + + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(pluginMap); + + on(pluginMap, 'defined', bind(this, function (plugin) { + var load, normalizedMap, normalizedMod, + bundleId = getOwn(bundlesMap, this.map.id), + name = this.map.name, + parentName = this.map.parentMap ? this.map.parentMap.name : null, + localRequire = context.makeRequire(map.parentMap, { + enableBuildCallback: true + }); + + //If current map is not normalized, wait for that + //normalized name to load instead of continuing. + if (this.map.unnormalized) { + //Normalize the ID if the plugin allows it. + if (plugin.normalize) { + name = plugin.normalize(name, function (name) { + return normalize(name, parentName, true); + }) || ''; + } + + //prefix and name should already be normalized, no need + //for applying map config again either. + normalizedMap = makeModuleMap(map.prefix + '!' + name, + this.map.parentMap, + true); + on(normalizedMap, + 'defined', bind(this, function (value) { + this.map.normalizedMap = normalizedMap; + this.init([], function () { return value; }, null, { + enabled: true, + ignore: true + }); + })); + + normalizedMod = getOwn(registry, normalizedMap.id); + if (normalizedMod) { + //Mark this as a dependency for this plugin, so it + //can be traced for cycles. + this.depMaps.push(normalizedMap); + + if (this.events.error) { + normalizedMod.on('error', bind(this, function (err) { + this.emit('error', err); + })); + } + normalizedMod.enable(); + } + + return; + } + + //If a paths config, then just load that file instead to + //resolve the plugin, as it is built into that paths layer. + if (bundleId) { + this.map.url = context.nameToUrl(bundleId); + this.load(); + return; + } + + load = bind(this, function (value) { + this.init([], function () { return value; }, null, { + enabled: true + }); + }); + + load.error = bind(this, function (err) { + this.inited = true; + this.error = err; + err.requireModules = [id]; + + //Remove temp unnormalized modules for this module, + //since they will never be resolved otherwise now. + eachProp(registry, function (mod) { + if (mod.map.id.indexOf(id + '_unnormalized') === 0) { + cleanRegistry(mod.map.id); + } + }); + + onError(err); + }); + + //Allow plugins to load other code without having to know the + //context or how to 'complete' the load. + load.fromText = bind(this, function (text, textAlt) { + /*jslint evil: true */ + var moduleName = map.name, + moduleMap = makeModuleMap(moduleName), + hasInteractive = useInteractive; + + //As of 2.1.0, support just passing the text, to reinforce + //fromText only being called once per resource. Still + //support old style of passing moduleName but discard + //that moduleName in favor of the internal ref. + if (textAlt) { + text = textAlt; + } + + //Turn off interactive script matching for IE for any define + //calls in the text, then turn it back on at the end. + if (hasInteractive) { + useInteractive = false; + } + + //Prime the system by creating a module instance for + //it. + getModule(moduleMap); + + //Transfer any config to this other module. + if (hasProp(config.config, id)) { + config.config[moduleName] = config.config[id]; + } + + try { + req.exec(text); + } catch (e) { + return onError(makeError('fromtexteval', + 'fromText eval for ' + id + + ' failed: ' + e, + e, + [id])); + } + + if (hasInteractive) { + useInteractive = true; + } + + //Mark this as a dependency for the plugin + //resource + this.depMaps.push(moduleMap); + + //Support anonymous modules. + context.completeLoad(moduleName); + + //Bind the value of that module to the value for this + //resource ID. + localRequire([moduleName], load); + }); + + //Use parentName here since the plugin's name is not reliable, + //could be some weird string with no path that actually wants to + //reference the parentName's path. + plugin.load(map.name, localRequire, load, config); + })); + + context.enable(pluginMap, this); + this.pluginMaps[pluginMap.id] = pluginMap; + }, + + enable: function () { + enabledRegistry[this.map.id] = this; + this.enabled = true; + + //Set flag mentioning that the module is enabling, + //so that immediate calls to the defined callbacks + //for dependencies do not trigger inadvertent load + //with the depCount still being zero. + this.enabling = true; + + //Enable each dependency + each(this.depMaps, bind(this, function (depMap, i) { + var id, mod, handler; + + if (typeof depMap === 'string') { + //Dependency needs to be converted to a depMap + //and wired up to this module. + depMap = makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, + !this.skipMap); + this.depMaps[i] = depMap; + + handler = getOwn(handlers, depMap.id); + + if (handler) { + this.depExports[i] = handler(this); + return; + } + + this.depCount += 1; + + on(depMap, 'defined', bind(this, function (depExports) { + if (this.undefed) { + return; + } + this.defineDep(i, depExports); + this.check(); + })); + + if (this.errback) { + on(depMap, 'error', bind(this, this.errback)); + } else if (this.events.error) { + // No direct errback on this module, but something + // else is listening for errors, so be sure to + // propagate the error correctly. + on(depMap, 'error', bind(this, function(err) { + this.emit('error', err); + })); + } + } + + id = depMap.id; + mod = registry[id]; + + //Skip special modules like 'require', 'exports', 'module' + //Also, don't call enable if it is already enabled, + //important in circular dependency cases. + if (!hasProp(handlers, id) && mod && !mod.enabled) { + context.enable(depMap, this); + } + })); + + //Enable each plugin that is used in + //a dependency + eachProp(this.pluginMaps, bind(this, function (pluginMap) { + var mod = getOwn(registry, pluginMap.id); + if (mod && !mod.enabled) { + context.enable(pluginMap, this); + } + })); + + this.enabling = false; + + this.check(); + }, + + on: function (name, cb) { + var cbs = this.events[name]; + if (!cbs) { + cbs = this.events[name] = []; + } + cbs.push(cb); + }, + + emit: function (name, evt) { + each(this.events[name], function (cb) { + cb(evt); + }); + if (name === 'error') { + //Now that the error handler was triggered, remove + //the listeners, since this broken Module instance + //can stay around for a while in the registry. + delete this.events[name]; + } + } + }; + + function callGetModule(args) { + //Skip modules already defined. + if (!hasProp(defined, args[0])) { + getModule(makeModuleMap(args[0], null, true)).init(args[1], args[2]); + } + } + + function removeListener(node, func, name, ieName) { + //Favor detachEvent because of IE9 + //issue, see attachEvent/addEventListener comment elsewhere + //in this file. + if (node.detachEvent && !isOpera) { + //Probably IE. If not it will throw an error, which will be + //useful to know. + if (ieName) { + node.detachEvent(ieName, func); + } + } else { + node.removeEventListener(name, func, false); + } + } + + /** + * Given an event from a script node, get the requirejs info from it, + * and then removes the event listeners on the node. + * @param {Event} evt + * @returns {Object} + */ + function getScriptData(evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + var node = evt.currentTarget || evt.srcElement; + + //Remove the listeners once here. + removeListener(node, context.onScriptLoad, 'load', 'onreadystatechange'); + removeListener(node, context.onScriptError, 'error'); + + return { + node: node, + id: node && node.getAttribute('data-requiremodule') + }; + } + + function intakeDefines() { + var args; + + //Any defined modules in the global queue, intake them now. + takeGlobalQueue(); + + //Make sure any remaining defQueue items get properly processed. + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + return onError(makeError('mismatch', 'Mismatched anonymous define() module: ' + + args[args.length - 1])); + } else { + //args are id, deps, factory. Should be normalized by the + //define() function. + callGetModule(args); + } + } + context.defQueueMap = {}; + } + + context = { + config: config, + contextName: contextName, + registry: registry, + defined: defined, + urlFetched: urlFetched, + defQueue: defQueue, + defQueueMap: {}, + Module: Module, + makeModuleMap: makeModuleMap, + nextTick: req.nextTick, + onError: onError, + + /** + * Set a configuration for the context. + * @param {Object} cfg config object to integrate. + */ + configure: function (cfg) { + //Make sure the baseUrl ends in a slash. + if (cfg.baseUrl) { + if (cfg.baseUrl.charAt(cfg.baseUrl.length - 1) !== '/') { + cfg.baseUrl += '/'; + } + } + + // Convert old style urlArgs string to a function. + if (typeof cfg.urlArgs === 'string') { + var urlArgs = cfg.urlArgs; + cfg.urlArgs = function(id, url) { + return (url.indexOf('?') === -1 ? '?' : '&') + urlArgs; + }; + } + + //Save off the paths since they require special processing, + //they are additive. + var shim = config.shim, + objs = { + paths: true, + bundles: true, + config: true, + map: true + }; + + eachProp(cfg, function (value, prop) { + if (objs[prop]) { + if (!config[prop]) { + config[prop] = {}; + } + mixin(config[prop], value, true, true); + } else { + config[prop] = value; + } + }); + + //Reverse map the bundles + if (cfg.bundles) { + eachProp(cfg.bundles, function (value, prop) { + each(value, function (v) { + if (v !== prop) { + bundlesMap[v] = prop; + } + }); + }); + } + + //Merge shim + if (cfg.shim) { + eachProp(cfg.shim, function (value, id) { + //Normalize the structure + if (isArray(value)) { + value = { + deps: value + }; + } + if ((value.exports || value.init) && !value.exportsFn) { + value.exportsFn = context.makeShimExports(value); + } + shim[id] = value; + }); + config.shim = shim; + } + + //Adjust packages if necessary. + if (cfg.packages) { + each(cfg.packages, function (pkgObj) { + var location, name; + + pkgObj = typeof pkgObj === 'string' ? {name: pkgObj} : pkgObj; + + name = pkgObj.name; + location = pkgObj.location; + if (location) { + config.paths[name] = pkgObj.location; + } + + //Save pointer to main module ID for pkg name. + //Remove leading dot in main, so main paths are normalized, + //and remove any trailing .js, since different package + //envs have different conventions: some use a module name, + //some use a file name. + config.pkgs[name] = pkgObj.name + '/' + (pkgObj.main || 'main') + .replace(currDirRegExp, '') + .replace(jsSuffixRegExp, ''); + }); + } + + //If there are any "waiting to execute" modules in the registry, + //update the maps for them, since their info, like URLs to load, + //may have changed. + eachProp(registry, function (mod, id) { + //If module already has init called, since it is too + //late to modify them, and ignore unnormalized ones + //since they are transient. + if (!mod.inited && !mod.map.unnormalized) { + mod.map = makeModuleMap(id, null, true); + } + }); + + //If a deps array or a config callback is specified, then call + //require with those args. This is useful when require is defined as a + //config object before require.js is loaded. + if (cfg.deps || cfg.callback) { + context.require(cfg.deps || [], cfg.callback); + } + }, + + makeShimExports: function (value) { + function fn() { + var ret; + if (value.init) { + ret = value.init.apply(global, arguments); + } + return ret || (value.exports && getGlobal(value.exports)); + } + return fn; + }, + + makeRequire: function (relMap, options) { + options = options || {}; + + function localRequire(deps, callback, errback) { + var id, map, requireMod; + + if (options.enableBuildCallback && callback && isFunction(callback)) { + callback.__requireJsBuild = true; + } + + if (typeof deps === 'string') { + if (isFunction(callback)) { + //Invalid call + return onError(makeError('requireargs', 'Invalid require call'), errback); + } + + //If require|exports|module are requested, get the + //value for them from the special handlers. Caveat: + //this only works while module is being defined. + if (relMap && hasProp(handlers, deps)) { + return handlers[deps](registry[relMap.id]); + } + + //Synchronous access to one module. If require.get is + //available (as in the Node adapter), prefer that. + if (req.get) { + return req.get(context, deps, relMap, localRequire); + } + + //Normalize module name, if it contains . or .. + map = makeModuleMap(deps, relMap, false, true); + id = map.id; + + if (!hasProp(defined, id)) { + return onError(makeError('notloaded', 'Module name "' + + id + + '" has not been loaded yet for context: ' + + contextName + + (relMap ? '' : '. Use require([])'))); + } + return defined[id]; + } + + //Grab defines waiting in the global queue. + intakeDefines(); + + //Mark all the dependencies as needing to be loaded. + context.nextTick(function () { + //Some defines could have been added since the + //require call, collect them. + intakeDefines(); + + requireMod = getModule(makeModuleMap(null, relMap)); + + //Store if map config should be applied to this require + //call for dependencies. + requireMod.skipMap = options.skipMap; + + requireMod.init(deps, callback, errback, { + enabled: true + }); + + checkLoaded(); + }); + + return localRequire; + } + + mixin(localRequire, { + isBrowser: isBrowser, + + /** + * Converts a module name + .extension into an URL path. + * *Requires* the use of a module name. It does not support using + * plain URLs like nameToUrl. + */ + toUrl: function (moduleNamePlusExt) { + var ext, + index = moduleNamePlusExt.lastIndexOf('.'), + segment = moduleNamePlusExt.split('/')[0], + isRelative = segment === '.' || segment === '..'; + + //Have a file extension alias, and it is not the + //dots from a relative path. + if (index !== -1 && (!isRelative || index > 1)) { + ext = moduleNamePlusExt.substring(index, moduleNamePlusExt.length); + moduleNamePlusExt = moduleNamePlusExt.substring(0, index); + } + + return context.nameToUrl(normalize(moduleNamePlusExt, + relMap && relMap.id, true), ext, true); + }, + + defined: function (id) { + return hasProp(defined, makeModuleMap(id, relMap, false, true).id); + }, + + specified: function (id) { + id = makeModuleMap(id, relMap, false, true).id; + return hasProp(defined, id) || hasProp(registry, id); + } + }); + + //Only allow undef on top level require calls + if (!relMap) { + localRequire.undef = function (id) { + //Bind any waiting define() calls to this context, + //fix for #408 + takeGlobalQueue(); + + var map = makeModuleMap(id, relMap, true), + mod = getOwn(registry, id); + + mod.undefed = true; + removeScript(id); + + delete defined[id]; + delete urlFetched[map.url]; + delete undefEvents[id]; + + //Clean queued defines too. Go backwards + //in array so that the splices do not + //mess up the iteration. + eachReverse(defQueue, function(args, i) { + if (args[0] === id) { + defQueue.splice(i, 1); + } + }); + delete context.defQueueMap[id]; + + if (mod) { + //Hold on to listeners in case the + //module will be attempted to be reloaded + //using a different config. + if (mod.events.defined) { + undefEvents[id] = mod.events; + } + + cleanRegistry(id); + } + }; + } + + return localRequire; + }, + + /** + * Called to enable a module if it is still in the registry + * awaiting enablement. A second arg, parent, the parent module, + * is passed in for context, when this method is overridden by + * the optimizer. Not shown here to keep code compact. + */ + enable: function (depMap) { + var mod = getOwn(registry, depMap.id); + if (mod) { + getModule(depMap).enable(); + } + }, + + /** + * Internal method used by environment adapters to complete a load event. + * A load event could be a script load or just a load pass from a synchronous + * load call. + * @param {String} moduleName the name of the module to potentially complete. + */ + completeLoad: function (moduleName) { + var found, args, mod, + shim = getOwn(config.shim, moduleName) || {}, + shExports = shim.exports; + + takeGlobalQueue(); + + while (defQueue.length) { + args = defQueue.shift(); + if (args[0] === null) { + args[0] = moduleName; + //If already found an anonymous module and bound it + //to this name, then this is some other anon module + //waiting for its completeLoad to fire. + if (found) { + break; + } + found = true; + } else if (args[0] === moduleName) { + //Found matching define call for this script! + found = true; + } + + callGetModule(args); + } + context.defQueueMap = {}; + + //Do this after the cycle of callGetModule in case the result + //of those calls/init calls changes the registry. + mod = getOwn(registry, moduleName); + + if (!found && !hasProp(defined, moduleName) && mod && !mod.inited) { + if (config.enforceDefine && (!shExports || !getGlobal(shExports))) { + if (hasPathFallback(moduleName)) { + return; + } else { + return onError(makeError('nodefine', + 'No define call for ' + moduleName, + null, + [moduleName])); + } + } else { + //A script that does not call define(), so just simulate + //the call for it. + callGetModule([moduleName, (shim.deps || []), shim.exportsFn]); + } + } + + checkLoaded(); + }, + + /** + * Converts a module name to a file path. Supports cases where + * moduleName may actually be just an URL. + * Note that it **does not** call normalize on the moduleName, + * it is assumed to have already been normalized. This is an + * internal API, not a public one. Use toUrl for the public API. + */ + nameToUrl: function (moduleName, ext, skipExt) { + var paths, syms, i, parentModule, url, + parentPath, bundleId, + pkgMain = getOwn(config.pkgs, moduleName); + + if (pkgMain) { + moduleName = pkgMain; + } + + bundleId = getOwn(bundlesMap, moduleName); + + if (bundleId) { + return context.nameToUrl(bundleId, ext, skipExt); + } + + //If a colon is in the URL, it indicates a protocol is used and it is just + //an URL to a file, or if it starts with a slash, contains a query arg (i.e. ?) + //or ends with .js, then assume the user meant to use an url and not a module id. + //The slash is important for protocol-less URLs as well as full paths. + if (req.jsExtRegExp.test(moduleName)) { + //Just a plain path, not module name lookup, so just return it. + //Add extension if it is included. This is a bit wonky, only non-.js things pass + //an extension, this method probably needs to be reworked. + url = moduleName + (ext || ''); + } else { + //A module that needs to be converted to a path. + paths = config.paths; + + syms = moduleName.split('/'); + //For each module name segment, see if there is a path + //registered for it. Start with most specific name + //and work up from it. + for (i = syms.length; i > 0; i -= 1) { + parentModule = syms.slice(0, i).join('/'); + + parentPath = getOwn(paths, parentModule); + if (parentPath) { + //If an array, it means there are a few choices, + //Choose the one that is desired + if (isArray(parentPath)) { + parentPath = parentPath[0]; + } + syms.splice(0, i, parentPath); + break; + } + } + + //Join the path parts together, then figure out if baseUrl is needed. + url = syms.join('/'); + url += (ext || (/^data\:|^blob\:|\?/.test(url) || skipExt ? '' : '.js')); + url = (url.charAt(0) === '/' || url.match(/^[\w\+\.\-]+:/) ? '' : config.baseUrl) + url; + } + + return config.urlArgs && !/^blob\:/.test(url) ? + url + config.urlArgs(moduleName, url) : url; + }, + + //Delegates to req.load. Broken out as a separate function to + //allow overriding in the optimizer. + load: function (id, url) { + req.load(context, id, url); + }, + + /** + * Executes a module callback function. Broken out as a separate function + * solely to allow the build system to sequence the files in the built + * layer in the right sequence. + * + * @private + */ + execCb: function (name, callback, args, exports) { + return callback.apply(exports, args); + }, + + /** + * callback for script loads, used to check status of loading. + * + * @param {Event} evt the event from the browser for the script + * that was loaded. + */ + onScriptLoad: function (evt) { + //Using currentTarget instead of target for Firefox 2.0's sake. Not + //all old browsers will be supported, but this one was easy enough + //to support and still makes sense. + if (evt.type === 'load' || + (readyRegExp.test((evt.currentTarget || evt.srcElement).readyState))) { + //Reset interactive script so a script node is not held onto for + //to long. + interactiveScript = null; + + //Pull out the name of the module and the context. + var data = getScriptData(evt); + context.completeLoad(data.id); + } + }, + + /** + * Callback for script errors. + */ + onScriptError: function (evt) { + var data = getScriptData(evt); + if (!hasPathFallback(data.id)) { + var parents = []; + eachProp(registry, function(value, key) { + if (key.indexOf('_@r') !== 0) { + each(value.depMaps, function(depMap) { + if (depMap.id === data.id) { + parents.push(key); + return true; + } + }); + } + }); + return onError(makeError('scripterror', 'Script error for "' + data.id + + (parents.length ? + '", needed by: ' + parents.join(', ') : + '"'), evt, [data.id])); + } + } + }; + + context.require = context.makeRequire(); + return context; + } + + /** + * Main entry point. + * + * If the only argument to require is a string, then the module that + * is represented by that string is fetched for the appropriate context. + * + * If the first argument is an array, then it will be treated as an array + * of dependency string names to fetch. An optional function callback can + * be specified to execute when all of those dependencies are available. + * + * Make a local req variable to help Caja compliance (it assumes things + * on a require that are not standardized), and to give a short + * name for minification/local scope use. + */ + req = requirejs = function (deps, callback, errback, optional) { + + //Find the right context, use default + var context, config, + contextName = defContextName; + + // Determine if have config object in the call. + if (!isArray(deps) && typeof deps !== 'string') { + // deps is a config object + config = deps; + if (isArray(callback)) { + // Adjust args if there are dependencies + deps = callback; + callback = errback; + errback = optional; + } else { + deps = []; + } + } + + if (config && config.context) { + contextName = config.context; + } + + context = getOwn(contexts, contextName); + if (!context) { + context = contexts[contextName] = req.s.newContext(contextName); + } + + if (config) { + context.configure(config); + } + + return context.require(deps, callback, errback); + }; + + /** + * Support require.config() to make it easier to cooperate with other + * AMD loaders on globally agreed names. + */ + req.config = function (config) { + return req(config); + }; + + /** + * Execute something after the current tick + * of the event loop. Override for other envs + * that have a better solution than setTimeout. + * @param {Function} fn function to execute later. + */ + req.nextTick = typeof setTimeout !== 'undefined' ? function (fn) { + setTimeout(fn, 4); + } : function (fn) { fn(); }; + + /** + * Export require as a global, but only if it does not already exist. + */ + if (!require) { + require = req; + } + + req.version = version; + + //Used to filter out dependencies that are already paths. + req.jsExtRegExp = /^\/|:|\?|\.js$/; + req.isBrowser = isBrowser; + s = req.s = { + contexts: contexts, + newContext: newContext + }; + + //Create default context. + req({}); + + //Exports some context-sensitive methods on global require. + each([ + 'toUrl', + 'undef', + 'defined', + 'specified' + ], function (prop) { + //Reference from contexts instead of early binding to default context, + //so that during builds, the latest instance of the default context + //with its config gets used. + req[prop] = function () { + var ctx = contexts[defContextName]; + return ctx.require[prop].apply(ctx, arguments); + }; + }); + + if (isBrowser) { + head = s.head = document.getElementsByTagName('head')[0]; + //If BASE tag is in play, using appendChild is a problem for IE6. + //When that browser dies, this can be removed. Details in this jQuery bug: + //http://dev.jquery.com/ticket/2709 + baseElement = document.getElementsByTagName('base')[0]; + if (baseElement) { + head = s.head = baseElement.parentNode; + } + } + + /** + * Any errors that require explicitly generates will be passed to this + * function. Intercept/override it if you want custom error handling. + * @param {Error} err the error object. + */ + req.onError = defaultOnError; + + /** + * Creates the node for the load command. Only used in browser envs. + */ + req.createNode = function (config, moduleName, url) { + var node = config.xhtml ? + document.createElementNS('http://www.w3.org/1999/xhtml', 'html:script') : + document.createElement('script'); + node.type = config.scriptType || 'text/javascript'; + node.charset = 'utf-8'; + node.async = true; + return node; + }; + + /** + * Does the request to load a module for the browser case. + * Make this a separate function to allow other environments + * to override it. + * + * @param {Object} context the require context to find state. + * @param {String} moduleName the name of the module. + * @param {Object} url the URL to the module. + */ + req.load = function (context, moduleName, url) { + var config = (context && context.config) || {}, + node; + if (isBrowser) { + //In the browser so use a script tag + node = req.createNode(config, moduleName, url); + + node.setAttribute('data-requirecontext', context.contextName); + node.setAttribute('data-requiremodule', moduleName); + + //Set up load listener. Test attachEvent first because IE9 has + //a subtle issue in its addEventListener and script onload firings + //that do not match the behavior of all other browsers with + //addEventListener support, which fire the onload event for a + //script right after the script execution. See: + //https://connect.microsoft.com/IE/feedback/details/648057/script-onload-event-is-not-fired-immediately-after-script-execution + //UNFORTUNATELY Opera implements attachEvent but does not follow the script + //script execution mode. + if (node.attachEvent && + //Check if node.attachEvent is artificially added by custom script or + //natively supported by browser + //read https://github.com/requirejs/requirejs/issues/187 + //if we can NOT find [native code] then it must NOT natively supported. + //in IE8, node.attachEvent does not have toString() + //Note the test for "[native code" with no closing brace, see: + //https://github.com/requirejs/requirejs/issues/273 + !(node.attachEvent.toString && node.attachEvent.toString().indexOf('[native code') < 0) && + !isOpera) { + //Probably IE. IE (at least 6-8) do not fire + //script onload right after executing the script, so + //we cannot tie the anonymous define call to a name. + //However, IE reports the script as being in 'interactive' + //readyState at the time of the define call. + useInteractive = true; + + node.attachEvent('onreadystatechange', context.onScriptLoad); + //It would be great to add an error handler here to catch + //404s in IE9+. However, onreadystatechange will fire before + //the error handler, so that does not help. If addEventListener + //is used, then IE will fire error before load, but we cannot + //use that pathway given the connect.microsoft.com issue + //mentioned above about not doing the 'script execute, + //then fire the script load event listener before execute + //next script' that other browsers do. + //Best hope: IE10 fixes the issues, + //and then destroys all installs of IE 6-9. + //node.attachEvent('onerror', context.onScriptError); + } else { + node.addEventListener('load', context.onScriptLoad, false); + node.addEventListener('error', context.onScriptError, false); + } + node.src = url; + + //Calling onNodeCreated after all properties on the node have been + //set, but before it is placed in the DOM. + if (config.onNodeCreated) { + config.onNodeCreated(node, config, moduleName, url); + } + + //For some cache cases in IE 6-8, the script executes before the end + //of the appendChild execution, so to tie an anonymous define + //call to the module name (which is stored on the node), hold on + //to a reference to this node, but clear after the DOM insertion. + currentlyAddingScript = node; + if (baseElement) { + head.insertBefore(node, baseElement); + } else { + head.appendChild(node); + } + currentlyAddingScript = null; + + return node; + } else if (isWebWorker) { + try { + //In a web worker, use importScripts. This is not a very + //efficient use of importScripts, importScripts will block until + //its script is downloaded and evaluated. However, if web workers + //are in play, the expectation is that a build has been done so + //that only one script needs to be loaded anyway. This may need + //to be reevaluated if other use cases become common. + + // Post a task to the event loop to work around a bug in WebKit + // where the worker gets garbage-collected after calling + // importScripts(): https://webkit.org/b/153317 + setTimeout(function() {}, 0); + importScripts(url); + + //Account for anonymous modules + context.completeLoad(moduleName); + } catch (e) { + context.onError(makeError('importscripts', + 'importScripts failed for ' + + moduleName + ' at ' + url, + e, + [moduleName])); + } + } + }; + + function getInteractiveScript() { + if (interactiveScript && interactiveScript.readyState === 'interactive') { + return interactiveScript; + } + + eachReverse(scripts(), function (script) { + if (script.readyState === 'interactive') { + return (interactiveScript = script); + } + }); + return interactiveScript; + } + + //Look for a data-main script attribute, which could also adjust the baseUrl. + if (isBrowser && !cfg.skipDataMain) { + //Figure out baseUrl. Get it from the script tag with require.js in it. + eachReverse(scripts(), function (script) { + //Set the 'head' where we can append children by + //using the script's parent. + if (!head) { + head = script.parentNode; + } + + //Look for a data-main attribute to set main script for the page + //to load. If it is there, the path to data main becomes the + //baseUrl, if it is not already set. + dataMain = script.getAttribute('data-main'); + if (dataMain) { + //Preserve dataMain in case it is a path (i.e. contains '?') + mainScript = dataMain; + + //Set final baseUrl if there is not already an explicit one, + //but only do so if the data-main value is not a loader plugin + //module ID. + if (!cfg.baseUrl && mainScript.indexOf('!') === -1) { + //Pull off the directory of data-main for use as the + //baseUrl. + src = mainScript.split('/'); + mainScript = src.pop(); + subPath = src.length ? src.join('/') + '/' : './'; + + cfg.baseUrl = subPath; + } + + //Strip off any trailing .js since mainScript is now + //like a module name. + mainScript = mainScript.replace(jsSuffixRegExp, ''); + + //If mainScript is still a path, fall back to dataMain + if (req.jsExtRegExp.test(mainScript)) { + mainScript = dataMain; + } + + //Put the data-main script in the files to load. + cfg.deps = cfg.deps ? cfg.deps.concat(mainScript) : [mainScript]; + + return true; + } + }); + } + + /** + * The function that handles definitions of modules. Differs from + * require() in that a string for the module should be the first argument, + * and the function to execute after dependencies are loaded should + * return a value to define the module corresponding to the first argument's + * name. + */ + define = function (name, deps, callback) { + var node, context; + + //Allow for anonymous modules + if (typeof name !== 'string') { + //Adjust args appropriately + callback = deps; + deps = name; + name = null; + } + + //This module may not have dependencies + if (!isArray(deps)) { + callback = deps; + deps = null; + } + + //If no name, and callback is a function, then figure out if it a + //CommonJS thing with dependencies. + if (!deps && isFunction(callback)) { + deps = []; + //Remove comments from the callback string, + //look for require calls, and pull them into the dependencies, + //but only if there are function args. + if (callback.length) { + callback + .toString() + .replace(commentRegExp, commentReplace) + .replace(cjsRequireRegExp, function (match, dep) { + deps.push(dep); + }); + + //May be a CommonJS thing even without require calls, but still + //could use exports, and module. Avoid doing exports and module + //work though if it just needs require. + //REQUIRES the function to expect the CommonJS variables in the + //order listed below. + deps = (callback.length === 1 ? ['require'] : ['require', 'exports', 'module']).concat(deps); + } + } + + //If in IE 6-8 and hit an anonymous define() call, do the interactive + //work. + if (useInteractive) { + node = currentlyAddingScript || getInteractiveScript(); + if (node) { + if (!name) { + name = node.getAttribute('data-requiremodule'); + } + context = contexts[node.getAttribute('data-requirecontext')]; + } + } + + //Always save off evaluating the def call until the script onload handler. + //This allows multiple modules to be in a file without prematurely + //tracing dependencies, and allows for anonymous module support, + //where the module name is not known until the script onload event + //occurs. If no context, use the global queue, and get it processed + //in the onscript load callback. + if (context) { + context.defQueue.push([name, deps, callback]); + context.defQueueMap[name] = true; + } else { + globalDefQueue.push([name, deps, callback]); + } + }; + + define.amd = { + jQuery: true + }; + + /** + * Executes the text. Normally just uses eval, but can be modified + * to use a better, environment-specific call. Only used for transpiling + * loader plugins, not for plain JS modules. + * @param {String} text the text to execute/evaluate. + */ + req.exec = function (text) { + /*jslint evil: true */ + return eval(text); + }; + + //Set up with config info. + req(cfg); +}(this, (typeof setTimeout === 'undefined' ? undefined : setTimeout))); + + + + this.requirejsVars = { + require: require, + requirejs: require, + define: define + }; + + if (env === 'browser') { + //sloppy since eval enclosed with use strict causes problems if the source +//text is not strict-compliant. +/*jslint sloppy: true, evil: true */ +/*global require, XMLHttpRequest */ + +(function () { + // Separate function to avoid eval pollution, same with arguments use. + function exec() { + eval(arguments[0]); + } + + require.load = function (context, moduleName, url) { + var xhr = new XMLHttpRequest(); + + xhr.open('GET', url, true); + xhr.send(); + + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + exec(xhr.responseText); + + //Support anonymous modules. + context.completeLoad(moduleName); + } + }; + }; +}()); + } else if (env === 'rhino') { + /*global require: false, java: false, load: false */ + +(function () { + 'use strict'; + require.load = function (context, moduleName, url) { + + load(url); + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + +}()); + } else if (env === 'node') { + this.requirejsVars.nodeRequire = nodeRequire; + require.nodeRequire = nodeRequire; + + //Explicity not strict since this file contains an eval call, and do not want +//to enforce strict on code evaluated that way. See +//https://github.com/requirejs/r.js/issues/774 +/*jslint regexp: false, sloppy: true*/ +/*global require: false, define: false, requirejsVars: false, process: false */ + +/** + * This adapter assumes that x.js has loaded it and set up + * some variables. This adapter just allows limited RequireJS + * usage from within the requirejs directory. The general + * node adapater is r.js. + */ + +(function () { + var nodeReq = requirejsVars.nodeRequire, + req = requirejsVars.require, + def = requirejsVars.define, + fs = nodeReq('fs'), + path = nodeReq('path'), + vm = nodeReq('vm'), + //In Node 0.7+ existsSync is on fs. + exists = fs.existsSync || path.existsSync, + hasOwn = Object.prototype.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + function syncTick(fn) { + fn(); + } + + function makeError(message, moduleName) { + var err = new Error(message); + err.requireModules = [moduleName]; + return err; + } + + //Supply an implementation that allows synchronous get of a module. + req.get = function (context, moduleName, relModuleMap, localRequire) { + if (moduleName === "require" || moduleName === "exports" || moduleName === "module") { + context.onError(makeError("Explicit require of " + moduleName + " is not allowed.", moduleName)); + } + + var ret, oldTick, + moduleMap = context.makeModuleMap(moduleName, relModuleMap, false, true); + + //Normalize module name, if it contains . or .. + moduleName = moduleMap.id; + + if (hasProp(context.defined, moduleName)) { + ret = context.defined[moduleName]; + } else { + if (ret === undefined) { + //Make sure nextTick for this type of call is sync-based. + oldTick = context.nextTick; + context.nextTick = syncTick; + try { + if (moduleMap.prefix) { + //A plugin, call requirejs to handle it. Now that + //nextTick is syncTick, the require will complete + //synchronously. + localRequire([moduleMap.originalName]); + + //Now that plugin is loaded, can regenerate the moduleMap + //to get the final, normalized ID. + moduleMap = context.makeModuleMap(moduleMap.originalName, relModuleMap, false, true); + moduleName = moduleMap.id; + } else { + //Try to dynamically fetch it. + req.load(context, moduleName, moduleMap.url); + + //Enable the module + context.enable(moduleMap, relModuleMap); + } + + //Break any cycles by requiring it normally, but this will + //finish synchronously + context.require([moduleName]); + + //The above calls are sync, so can do the next thing safely. + ret = context.defined[moduleName]; + } finally { + context.nextTick = oldTick; + } + } + } + + return ret; + }; + + req.nextTick = function (fn) { + process.nextTick(fn); + }; + + //Add wrapper around the code so that it gets the requirejs + //API instead of the Node API, and it is done lexically so + //that it survives later execution. + req.makeNodeWrapper = function (contents) { + return '(function (require, requirejs, define) { ' + + contents + + '\n}(requirejsVars.require, requirejsVars.requirejs, requirejsVars.define));'; + }; + + req.load = function (context, moduleName, url) { + var contents, err, + config = context.config; + + if (config.shim[moduleName] && (!config.suppress || !config.suppress.nodeShim)) { + console.warn('Shim config not supported in Node, may or may not work. Detected ' + + 'for module: ' + moduleName); + } + + if (exists(url)) { + contents = fs.readFileSync(url, 'utf8'); + + contents = req.makeNodeWrapper(contents); + try { + vm.runInThisContext(contents, fs.realpathSync(url)); + } catch (e) { + err = new Error('Evaluating ' + url + ' as module "' + + moduleName + '" failed with error: ' + e); + err.originalError = e; + err.moduleName = moduleName; + err.requireModules = [moduleName]; + err.fileName = url; + return context.onError(err); + } + } else { + def(moduleName, function () { + //Get the original name, since relative requires may be + //resolved differently in node (issue #202). Also, if relative, + //make it relative to the URL of the item requesting it + //(issue #393) + var dirName, + map = hasProp(context.registry, moduleName) && + context.registry[moduleName].map, + parentMap = map && map.parentMap, + originalName = map && map.originalName; + + if (originalName.charAt(0) === '.' && parentMap) { + dirName = parentMap.url.split('/'); + dirName.pop(); + originalName = dirName.join('/') + '/' + originalName; + } + + try { + return (context.config.nodeRequire || req.nodeRequire)(originalName); + } catch (e) { + err = new Error('Tried loading "' + moduleName + '" at ' + + url + ' then tried node\'s require("' + + originalName + '") and it failed ' + + 'with error: ' + e); + err.originalError = e; + err.moduleName = originalName; + err.requireModules = [moduleName]; + throw err; + } + }); + } + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + + //Override to provide the function wrapper for define/require. + req.exec = function (text) { + /*jslint evil: true */ + text = req.makeNodeWrapper(text); + return eval(text); + }; +}()); + + } else if (env === 'xpconnect') { + /*jslint */ +/*global require, load */ + +(function () { + 'use strict'; + require.load = function (context, moduleName, url) { + + load(url); + + //Support anonymous modules. + context.completeLoad(moduleName); + }; + +}()); + + } + + //Support a default file name to execute. Useful for hosted envs + //like Joyent where it defaults to a server.js as the only executed + //script. But only do it if this is not an optimization run. + if (commandOption !== 'o' && (!fileName || !jsSuffixRegExp.test(fileName))) { + fileName = 'main.js'; + } + + /** + * Loads the library files that can be used for the optimizer, or for other + * tasks. + */ + function loadLib() { + /*jslint strict: false */ +/*global Packages: false, process: false, window: false, navigator: false, + document: false, define: false */ + +/** + * A plugin that modifies any /env/ path to be the right path based on + * the host environment. Right now only works for Node, Rhino and browser. + */ +(function () { + var pathRegExp = /(\/|^)env\/|\{env\}/, + env = 'unknown'; + + if (typeof process !== 'undefined' && process.versions && !!process.versions.node) { + env = 'node'; + } else if (typeof Packages !== 'undefined') { + env = 'rhino'; + } else if ((typeof navigator !== 'undefined' && typeof document !== 'undefined') || + (typeof importScripts !== 'undefined' && typeof self !== 'undefined')) { + env = 'browser'; + } else if (typeof Components !== 'undefined' && Components.classes && Components.interfaces) { + env = 'xpconnect'; + } + + define('env', { + get: function () { + return env; + }, + + load: function (name, req, load, config) { + //Allow override in the config. + if (config.env) { + env = config.env; + } + + name = name.replace(pathRegExp, function (match, prefix) { + if (match.indexOf('{') === -1) { + return prefix + env + '/'; + } else { + return env; + } + }); + + req([name], function (mod) { + load(mod); + }); + } + }); +}()); +/*jslint plusplus: true */ +/*global define, java */ + +define('lang', function () { + 'use strict'; + + var lang, isJavaObj, + hasOwn = Object.prototype.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + isJavaObj = function () { + return false; + }; + + //Rhino, but not Nashorn (detected by importPackage not existing) + //Can have some strange foreign objects. + if (typeof java !== 'undefined' && java.lang && java.lang.Object && typeof importPackage !== 'undefined') { + isJavaObj = function (obj) { + return obj instanceof java.lang.Object; + }; + } + + lang = { + backSlashRegExp: /\\/g, + ostring: Object.prototype.toString, + + isArray: Array.isArray || function (it) { + return lang.ostring.call(it) === "[object Array]"; + }, + + isFunction: function(it) { + return lang.ostring.call(it) === "[object Function]"; + }, + + isRegExp: function(it) { + return it && it instanceof RegExp; + }, + + hasProp: hasProp, + + //returns true if the object does not have an own property prop, + //or if it does, it is a falsy value. + falseProp: function (obj, prop) { + return !hasProp(obj, prop) || !obj[prop]; + }, + + //gets own property value for given prop on object + getOwn: function (obj, prop) { + return hasProp(obj, prop) && obj[prop]; + }, + + _mixin: function(dest, source, override){ + var name; + for (name in source) { + if(source.hasOwnProperty(name) && + (override || !dest.hasOwnProperty(name))) { + dest[name] = source[name]; + } + } + + return dest; // Object + }, + + /** + * mixin({}, obj1, obj2) is allowed. If the last argument is a boolean, + * then the source objects properties are force copied over to dest. + */ + mixin: function(dest){ + var parameters = Array.prototype.slice.call(arguments), + override, i, l; + + if (!dest) { dest = {}; } + + if (parameters.length > 2 && typeof arguments[parameters.length-1] === 'boolean') { + override = parameters.pop(); + } + + for (i = 1, l = parameters.length; i < l; i++) { + lang._mixin(dest, parameters[i], override); + } + return dest; // Object + }, + + /** + * Does a deep mix of source into dest, where source values override + * dest values if a winner is needed. + * @param {Object} dest destination object that receives the mixed + * values. + * @param {Object} source source object contributing properties to mix + * in. + * @return {[Object]} returns dest object with the modification. + */ + deepMix: function(dest, source) { + lang.eachProp(source, function (value, prop) { + if (typeof value === 'object' && value && + !lang.isArray(value) && !lang.isFunction(value) && + !(value instanceof RegExp)) { + + if (!dest[prop]) { + dest[prop] = {}; + } + lang.deepMix(dest[prop], value); + } else { + dest[prop] = value; + } + }); + return dest; + }, + + /** + * Does a type of deep copy. Do not give it anything fancy, best + * for basic object copies of objects that also work well as + * JSON-serialized things, or has properties pointing to functions. + * For non-array/object values, just returns the same object. + * @param {Object} obj copy properties from this object + * @param {Object} [ignoredProps] optional object whose own properties + * are keys that should be ignored. + * @return {Object} + */ + deeplikeCopy: function (obj, ignoredProps) { + var type, result; + + if (lang.isArray(obj)) { + result = []; + obj.forEach(function(value) { + result.push(lang.deeplikeCopy(value, ignoredProps)); + }); + return result; + } + + type = typeof obj; + if (obj === null || obj === undefined || type === 'boolean' || + type === 'string' || type === 'number' || lang.isFunction(obj) || + lang.isRegExp(obj)|| isJavaObj(obj)) { + return obj; + } + + //Anything else is an object, hopefully. + result = {}; + lang.eachProp(obj, function(value, key) { + if (!ignoredProps || !hasProp(ignoredProps, key)) { + result[key] = lang.deeplikeCopy(value, ignoredProps); + } + }); + return result; + }, + + delegate: (function () { + // boodman/crockford delegation w/ cornford optimization + function TMP() {} + return function (obj, props) { + TMP.prototype = obj; + var tmp = new TMP(); + TMP.prototype = null; + if (props) { + lang.mixin(tmp, props); + } + return tmp; // Object + }; + }()), + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + each: function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (func(ary[i], i, ary)) { + break; + } + } + } + }, + + /** + * Cycles over properties in an object and calls a function for each + * property value. If the function returns a truthy value, then the + * iteration is stopped. + */ + eachProp: function eachProp(obj, func) { + var prop; + for (prop in obj) { + if (hasProp(obj, prop)) { + if (func(obj[prop], prop)) { + break; + } + } + } + }, + + //Similar to Function.prototype.bind, but the "this" object is specified + //first, since it is easier to read/figure out what "this" will be. + bind: function bind(obj, fn) { + return function () { + return fn.apply(obj, arguments); + }; + }, + + //Escapes a content string to be be a string that has characters escaped + //for inclusion as part of a JS string. + jsEscape: function (content) { + return content.replace(/(["'\\])/g, '\\$1') + .replace(/[\f]/g, "\\f") + .replace(/[\b]/g, "\\b") + .replace(/[\n]/g, "\\n") + .replace(/[\t]/g, "\\t") + .replace(/[\r]/g, "\\r"); + } + }; + return lang; +}); +/** + * prim 0.0.1 Copyright (c) 2012-2014, The Dojo Foundation All Rights Reserved. + * Available via the MIT or new BSD license. + * see: http://github.com/requirejs/prim for details + */ + +/*global setImmediate, process, setTimeout, define, module */ + +//Set prime.hideResolutionConflict = true to allow "resolution-races" +//in promise-tests to pass. +//Since the goal of prim is to be a small impl for trusted code, it is +//more important to normally throw in this case so that we can find +//logic errors quicker. + +var prim; +(function () { + 'use strict'; + var op = Object.prototype, + hasOwn = op.hasOwnProperty; + + function hasProp(obj, prop) { + return hasOwn.call(obj, prop); + } + + /** + * Helper function for iterating over an array. If the func returns + * a true value, it will break out of the loop. + */ + function each(ary, func) { + if (ary) { + var i; + for (i = 0; i < ary.length; i += 1) { + if (ary[i]) { + func(ary[i], i, ary); + } + } + } + } + + function check(p) { + if (hasProp(p, 'e') || hasProp(p, 'v')) { + if (!prim.hideResolutionConflict) { + throw new Error('Prim promise already resolved: ' + + JSON.stringify(p)); + } + return false; + } + return true; + } + + function notify(ary, value) { + prim.nextTick(function () { + each(ary, function (item) { + item(value); + }); + }); + } + + prim = function prim() { + var p, + ok = [], + fail = []; + + return (p = { + callback: function (yes, no) { + if (no) { + p.errback(no); + } + + if (hasProp(p, 'v')) { + prim.nextTick(function () { + yes(p.v); + }); + } else { + ok.push(yes); + } + }, + + errback: function (no) { + if (hasProp(p, 'e')) { + prim.nextTick(function () { + no(p.e); + }); + } else { + fail.push(no); + } + }, + + finished: function () { + return hasProp(p, 'e') || hasProp(p, 'v'); + }, + + rejected: function () { + return hasProp(p, 'e'); + }, + + resolve: function (v) { + if (check(p)) { + p.v = v; + notify(ok, v); + } + return p; + }, + reject: function (e) { + if (check(p)) { + p.e = e; + notify(fail, e); + } + return p; + }, + + start: function (fn) { + p.resolve(); + return p.promise.then(fn); + }, + + promise: { + then: function (yes, no) { + var next = prim(); + + p.callback(function (v) { + try { + if (yes && typeof yes === 'function') { + v = yes(v); + } + + if (v && v.then) { + v.then(next.resolve, next.reject); + } else { + next.resolve(v); + } + } catch (e) { + next.reject(e); + } + }, function (e) { + var err; + + try { + if (!no || typeof no !== 'function') { + next.reject(e); + } else { + err = no(e); + + if (err && err.then) { + err.then(next.resolve, next.reject); + } else { + next.resolve(err); + } + } + } catch (e2) { + next.reject(e2); + } + }); + + return next.promise; + }, + + fail: function (no) { + return p.promise.then(null, no); + }, + + end: function () { + p.errback(function (e) { + throw e; + }); + } + } + }); + }; + + prim.serial = function (ary) { + var result = prim().resolve().promise; + each(ary, function (item) { + result = result.then(function () { + return item(); + }); + }); + return result; + }; + + prim.nextTick = typeof setImmediate === 'function' ? setImmediate : + (typeof process !== 'undefined' && process.nextTick ? + process.nextTick : (typeof setTimeout !== 'undefined' ? + function (fn) { + setTimeout(fn, 0); + } : function (fn) { + fn(); + })); + + if (typeof define === 'function' && define.amd) { + define('prim', function () { return prim; }); + } else if (typeof module !== 'undefined' && module.exports) { + module.exports = prim; + } +}()); +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('browser/assert', function () { + return {}; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Needed so that rhino/assert can return a stub for uglify's consolidator.js +define('node/assert', ['assert'], function (assert) { + return assert; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('rhino/assert', function () { + return {}; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, load: false */ + +//Just a stub for use with uglify's consolidator.js +define('xpconnect/assert', function () { + return {}; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, process: false */ + +define('browser/args', function () { + //Always expect config via an API call + return []; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, process: false */ + +define('node/args', function () { + //Do not return the "node" or "r.js" arguments + var args = process.argv.slice(2); + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, process: false */ + +var jsLibRhinoArgs = (typeof rhinoArgs !== 'undefined' && rhinoArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); + +define('rhino/args', function () { + var args = jsLibRhinoArgs; + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define, xpconnectArgs */ + +var jsLibXpConnectArgs = (typeof xpconnectArgs !== 'undefined' && xpconnectArgs) || [].concat(Array.prototype.slice.call(arguments, 0)); + +define('xpconnect/args', function () { + var args = jsLibXpConnectArgs; + + //Ignore any command option used for main x.js branching + if (args[0] && args[0].indexOf('-') === 0) { + args = args.slice(1); + } + + return args; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('browser/load', ['./file'], function (file) { + function load(fileName) { + eval(file.readFile(fileName)); + } + + return load; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('node/load', ['fs'], function (fs) { + function load(fileName) { + var contents = fs.readFileSync(fileName, 'utf8'); + process.compile(contents, fileName); + } + + return load; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, load: false */ + +define('rhino/load', function () { + return load; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, load: false */ + +define('xpconnect/load', function () { + return load; +}); + +} + +if(env === 'browser') { +/*jslint sloppy: true, nomen: true */ +/*global require, define, console, XMLHttpRequest, requirejs, location */ + +define('browser/file', ['prim'], function (prim) { + + var file, + currDirRegExp = /^\.(\/|$)/; + + function frontSlash(path) { + return path.replace(/\\/g, '/'); + } + + function exists(path) { + var status, xhr = new XMLHttpRequest(); + + //Oh yeah, that is right SYNC IO. Behold its glory + //and horrible blocking behavior. + xhr.open('HEAD', path, false); + xhr.send(); + status = xhr.status; + + return status === 200 || status === 304; + } + + function mkDir(dir) { + console.log('mkDir is no-op in browser'); + } + + function mkFullDir(dir) { + console.log('mkFullDir is no-op in browser'); + } + + file = { + backSlashRegExp: /\\/g, + exclusionRegExp: /^\./, + getLineSeparator: function () { + return '/'; + }, + + exists: function (fileName) { + return exists(fileName); + }, + + parent: function (fileName) { + var parts = fileName.split('/'); + parts.pop(); + return parts.join('/'); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {String} fileName + */ + absPath: function (fileName) { + var dir; + if (currDirRegExp.test(fileName)) { + dir = frontSlash(location.href); + if (dir.indexOf('/') !== -1) { + dir = dir.split('/'); + + //Pull off protocol and host, just want + //to allow paths (other build parts, like + //require._isSupportedBuildUrl do not support + //full URLs), but a full path from + //the root. + dir.splice(0, 3); + + dir.pop(); + dir = '/' + dir.join('/'); + } + + fileName = dir + fileName.substring(1); + } + + return fileName; + }, + + normalize: function (fileName) { + return fileName; + }, + + isFile: function (path) { + return true; + }, + + isDirectory: function (path) { + return false; + }, + + getFilteredFileList: function (startDir, regExpFilters, makeUnixPaths) { + console.log('file.getFilteredFileList is no-op in browser'); + }, + + copyDir: function (srcDir, destDir, regExpFilter, onlyCopyNew) { + console.log('file.copyDir is no-op in browser'); + + }, + + copyFile: function (srcFileName, destFileName, onlyCopyNew) { + console.log('file.copyFile is no-op in browser'); + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + console.log('file.renameFile is no-op in browser'); + }, + + /** + * Reads a *text* file. + */ + readFile: function (path, encoding) { + var xhr = new XMLHttpRequest(); + + //Oh yeah, that is right SYNC IO. Behold its glory + //and horrible blocking behavior. + xhr.open('GET', path, false); + xhr.send(); + + return xhr.responseText; + }, + + readFileAsync: function (path, encoding) { + var xhr = new XMLHttpRequest(), + d = prim(); + + xhr.open('GET', path, true); + xhr.send(); + + xhr.onreadystatechange = function () { + if (xhr.readyState === 4) { + if (xhr.status > 400) { + d.reject(new Error('Status: ' + xhr.status + ': ' + xhr.statusText)); + } else { + d.resolve(xhr.responseText); + } + } + }; + + return d.promise; + }, + + saveUtf8File: function (fileName, fileContents) { + //summary: saves a *text* file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf8"); + }, + + saveFile: function (fileName, fileContents, encoding) { + requirejs.browser.saveFile(fileName, fileContents, encoding); + }, + + deleteFile: function (fileName) { + console.log('file.deleteFile is no-op in browser'); + }, + + /** + * Deletes any empty directories under the given directory. + */ + deleteEmptyDirs: function (startDir) { + console.log('file.deleteEmptyDirs is no-op in browser'); + } + }; + + return file; + +}); + +} + +if(env === 'node') { +/*jslint plusplus: false, octal:false, strict: false */ +/*global define: false, process: false */ + +define('node/file', ['fs', 'path', 'prim'], function (fs, path, prim) { + + var isWindows = process.platform === 'win32', + windowsDriveRegExp = /^[a-zA-Z]\:\/$/, + file; + + function frontSlash(path) { + return path.replace(/\\/g, '/'); + } + + function exists(path) { + if (isWindows && path.charAt(path.length - 1) === '/' && + path.charAt(path.length - 2) !== ':') { + path = path.substring(0, path.length - 1); + } + + try { + fs.statSync(path); + return true; + } catch (e) { + return false; + } + } + + function mkDir(dir) { + if (!exists(dir) && (!isWindows || !windowsDriveRegExp.test(dir))) { + fs.mkdirSync(dir, 511); + } + } + + function mkFullDir(dir) { + var parts = dir.split('/'), + currDir = '', + first = true; + + parts.forEach(function (part) { + //First part may be empty string if path starts with a slash. + currDir += part + '/'; + first = false; + + if (part) { + mkDir(currDir); + } + }); + } + + file = { + backSlashRegExp: /\\/g, + exclusionRegExp: /^\./, + getLineSeparator: function () { + return '/'; + }, + + exists: function (fileName) { + return exists(fileName); + }, + + parent: function (fileName) { + var parts = fileName.split('/'); + parts.pop(); + return parts.join('/'); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {String} fileName + */ + absPath: function (fileName) { + return frontSlash(path.normalize(frontSlash(fs.realpathSync(fileName)))); + }, + + normalize: function (fileName) { + return frontSlash(path.normalize(fileName)); + }, + + isFile: function (path) { + return fs.statSync(path).isFile(); + }, + + isDirectory: function (path) { + return fs.statSync(path).isDirectory(); + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + i, stat, filePath, ok, dirFiles, fileName; + + topDir = startDir; + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (file.exists(topDir)) { + dirFileArray = fs.readdirSync(topDir); + for (i = 0; i < dirFileArray.length; i++) { + fileName = dirFileArray[i]; + filePath = path.join(topDir, fileName); + stat = fs.statSync(filePath); + if (stat.isFile()) { + if (makeUnixPaths) { + //Make sure we have a JS string. + if (filePath.indexOf("/") === -1) { + filePath = frontSlash(filePath); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileName))) { + files.push(filePath); + } + } else if (stat.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileName))) { + dirFiles = this.getFilteredFileList(filePath, regExpFilters, makeUnixPaths); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + //Normalize th directory names, but keep front slashes. + //path module on windows now returns backslashed paths. + srcDir = frontSlash(path.normalize(srcDir)); + destDir = frontSlash(path.normalize(destDir)); + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i++) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var parentDir; + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + if (file.exists(destFileName) && fs.statSync(destFileName).mtime.getTime() >= fs.statSync(srcFileName).mtime.getTime()) { + return false; //Boolean + } + } + + //Make sure destination dir exists. + parentDir = path.dirname(destFileName); + if (!file.exists(parentDir)) { + mkFullDir(parentDir); + } + + fs.writeFileSync(destFileName, fs.readFileSync(srcFileName, 'binary'), 'binary'); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + return fs.renameSync(from, to); + }, + + /** + * Reads a *text* file. + */ + readFile: function (/*String*/path, /*String?*/encoding) { + if (encoding === 'utf-8') { + encoding = 'utf8'; + } + if (!encoding) { + encoding = 'utf8'; + } + + var text = fs.readFileSync(path, encoding); + + //Hmm, would not expect to get A BOM, but it seems to happen, + //remove it just in case. + if (text.indexOf('\uFEFF') === 0) { + text = text.substring(1, text.length); + } + + return text; + }, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a *text* file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + //summary: saves a *text* file. + var parentDir; + + if (encoding === 'utf-8') { + encoding = 'utf8'; + } + if (!encoding) { + encoding = 'utf8'; + } + + //Make sure destination directories exist. + parentDir = path.dirname(fileName); + if (!file.exists(parentDir)) { + mkFullDir(parentDir); + } + + fs.writeFileSync(fileName, fileContents, encoding); + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var files, i, stat; + if (file.exists(fileName)) { + stat = fs.lstatSync(fileName); + if (stat.isDirectory()) { + files = fs.readdirSync(fileName); + for (i = 0; i < files.length; i++) { + this.deleteFile(path.join(fileName, files[i])); + } + fs.rmdirSync(fileName); + } else { + fs.unlinkSync(fileName); + } + } + }, + + + /** + * Deletes any empty directories under the given directory. + */ + deleteEmptyDirs: function (startDir) { + var dirFileArray, i, fileName, filePath, stat; + + if (file.exists(startDir)) { + dirFileArray = fs.readdirSync(startDir); + for (i = 0; i < dirFileArray.length; i++) { + fileName = dirFileArray[i]; + filePath = path.join(startDir, fileName); + stat = fs.lstatSync(filePath); + if (stat.isDirectory()) { + file.deleteEmptyDirs(filePath); + } + } + + //If directory is now empty, remove it. + if (fs.readdirSync(startDir).length === 0) { + file.deleteFile(startDir); + } + } + } + }; + + return file; + +}); + +} + +if(env === 'rhino') { +//Helper functions to deal with file I/O. + +/*jslint plusplus: false */ +/*global java: false, define: false */ + +define('rhino/file', ['prim'], function (prim) { + var file = { + backSlashRegExp: /\\/g, + + exclusionRegExp: /^\./, + + getLineSeparator: function () { + return file.lineSeparator; + }, + + lineSeparator: java.lang.System.getProperty("line.separator"), //Java String + + exists: function (fileName) { + return (new java.io.File(fileName)).exists(); + }, + + parent: function (fileName) { + return file.absPath((new java.io.File(fileName)).getParentFile()); + }, + + normalize: function (fileName) { + return file.absPath(fileName); + }, + + isFile: function (path) { + return (new java.io.File(path)).isFile(); + }, + + isDirectory: function (path) { + return (new java.io.File(path)).isDirectory(); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {java.io.File||String} file + */ + absPath: function (fileObj) { + if (typeof fileObj === "string") { + fileObj = new java.io.File(fileObj); + } + return (fileObj.getCanonicalPath() + "").replace(file.backSlashRegExp, "/"); + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsJavaObject) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + i, fileObj, filePath, ok, dirFiles; + + topDir = startDir; + if (!startDirIsJavaObject) { + topDir = new java.io.File(startDir); + } + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (topDir.exists()) { + dirFileArray = topDir.listFiles(); + for (i = 0; i < dirFileArray.length; i++) { + fileObj = dirFileArray[i]; + if (fileObj.isFile()) { + filePath = fileObj.getPath(); + if (makeUnixPaths) { + //Make sure we have a JS string. + filePath = String(filePath); + if (filePath.indexOf("/") === -1) { + filePath = filePath.replace(/\\/g, "/"); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileObj.getName()))) { + files.push(filePath); + } + } else if (fileObj.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.getName()))) { + dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i++) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var destFile = new java.io.File(destFileName), srcFile, parentDir, + srcChannel, destChannel; + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + srcFile = new java.io.File(srcFileName); + if (destFile.exists() && destFile.lastModified() >= srcFile.lastModified()) { + return false; //Boolean + } + } + + //Make sure destination dir exists. + parentDir = destFile.getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getCanonicalPath(); + } + } + + //Java's version of copy file. + srcChannel = new java.io.FileInputStream(srcFileName).getChannel(); + destChannel = new java.io.FileOutputStream(destFileName).getChannel(); + destChannel.transferFrom(srcChannel, 0, srcChannel.size()); + srcChannel.close(); + destChannel.close(); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + return (new java.io.File(from)).renameTo((new java.io.File(to))); + }, + + readFile: function (/*String*/path, /*String?*/encoding) { + //A file read function that can deal with BOMs + encoding = encoding || "utf-8"; + var fileObj = new java.io.File(path), + input = new java.io.BufferedReader(new java.io.InputStreamReader(new java.io.FileInputStream(fileObj), encoding)), + stringBuffer, line; + try { + stringBuffer = new java.lang.StringBuffer(); + line = input.readLine(); + + // Byte Order Mark (BOM) - The Unicode Standard, version 3.0, page 324 + // http://www.unicode.org/faq/utf_bom.html + + // Note that when we use utf-8, the BOM should appear as "EF BB BF", but it doesn't due to this bug in the JDK: + // http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4508058 + if (line && line.length() && line.charAt(0) === 0xfeff) { + // Eat the BOM, since we've already found the encoding on this file, + // and we plan to concatenating this buffer with others; the BOM should + // only appear at the top of a file. + line = line.substring(1); + } + while (line !== null) { + stringBuffer.append(line); + stringBuffer.append(file.lineSeparator); + line = input.readLine(); + } + //Make sure we return a JavaScript string and not a Java string. + return String(stringBuffer.toString()); //String + } finally { + input.close(); + } + }, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf-8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + //summary: saves a file. + var outFile = new java.io.File(fileName), outWriter, parentDir, os; + + parentDir = outFile.getAbsoluteFile().getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getAbsolutePath(); + } + } + + if (encoding) { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); + } else { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); + } + + os = new java.io.BufferedWriter(outWriter); + try { + //If in Nashorn, need to coerce the JS string to a Java string so that + //writer.write method dispatch correctly detects the type. + if (typeof importPackage !== 'undefined') { + os.write(fileContents); + } else { + os.write(new java.lang.String(fileContents)); + } + } finally { + os.close(); + } + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var fileObj = new java.io.File(fileName), files, i; + if (fileObj.exists()) { + if (fileObj.isDirectory()) { + files = fileObj.listFiles(); + for (i = 0; i < files.length; i++) { + this.deleteFile(files[i]); + } + } + fileObj["delete"](); + } + }, + + /** + * Deletes any empty directories under the given directory. + * The startDirIsJavaObject is private to this implementation's + * recursion needs. + */ + deleteEmptyDirs: function (startDir, startDirIsJavaObject) { + var topDir = startDir, + dirFileArray, i, fileObj; + + if (!startDirIsJavaObject) { + topDir = new java.io.File(startDir); + } + + if (topDir.exists()) { + dirFileArray = topDir.listFiles(); + for (i = 0; i < dirFileArray.length; i++) { + fileObj = dirFileArray[i]; + if (fileObj.isDirectory()) { + file.deleteEmptyDirs(fileObj, true); + } + } + + //If the directory is empty now, delete it. + if (topDir.listFiles().length === 0) { + file.deleteFile(String(topDir.getPath())); + } + } + } + }; + + return file; +}); + +} + +if(env === 'xpconnect') { +//Helper functions to deal with file I/O. + +/*jslint plusplus: false */ +/*global define, Components, xpcUtil */ + +define('xpconnect/file', ['prim'], function (prim) { + var file, + Cc = Components.classes, + Ci = Components.interfaces, + //Depends on xpcUtil which is set up in x.js + xpfile = xpcUtil.xpfile; + + function mkFullDir(dirObj) { + //1 is DIRECTORY_TYPE, 511 is 0777 permissions + if (!dirObj.exists()) { + dirObj.create(1, 511); + } + } + + file = { + backSlashRegExp: /\\/g, + + exclusionRegExp: /^\./, + + getLineSeparator: function () { + return file.lineSeparator; + }, + + lineSeparator: ('@mozilla.org/windows-registry-key;1' in Cc) ? + '\r\n' : '\n', + + exists: function (fileName) { + return xpfile(fileName).exists(); + }, + + parent: function (fileName) { + return xpfile(fileName).parent; + }, + + normalize: function (fileName) { + return file.absPath(fileName); + }, + + isFile: function (path) { + return xpfile(path).isFile(); + }, + + isDirectory: function (path) { + return xpfile(path).isDirectory(); + }, + + /** + * Gets the absolute file path as a string, normalized + * to using front slashes for path separators. + * @param {java.io.File||String} file + */ + absPath: function (fileObj) { + if (typeof fileObj === "string") { + fileObj = xpfile(fileObj); + } + return fileObj.path; + }, + + getFilteredFileList: function (/*String*/startDir, /*RegExp*/regExpFilters, /*boolean?*/makeUnixPaths, /*boolean?*/startDirIsObject) { + //summary: Recurses startDir and finds matches to the files that match regExpFilters.include + //and do not match regExpFilters.exclude. Or just one regexp can be passed in for regExpFilters, + //and it will be treated as the "include" case. + //Ignores files/directories that start with a period (.) unless exclusionRegExp + //is set to another value. + var files = [], topDir, regExpInclude, regExpExclude, dirFileArray, + fileObj, filePath, ok, dirFiles; + + topDir = startDir; + if (!startDirIsObject) { + topDir = xpfile(startDir); + } + + regExpInclude = regExpFilters.include || regExpFilters; + regExpExclude = regExpFilters.exclude || null; + + if (topDir.exists()) { + dirFileArray = topDir.directoryEntries; + while (dirFileArray.hasMoreElements()) { + fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); + if (fileObj.isFile()) { + filePath = fileObj.path; + if (makeUnixPaths) { + if (filePath.indexOf("/") === -1) { + filePath = filePath.replace(/\\/g, "/"); + } + } + + ok = true; + if (regExpInclude) { + ok = filePath.match(regExpInclude); + } + if (ok && regExpExclude) { + ok = !filePath.match(regExpExclude); + } + + if (ok && (!file.exclusionRegExp || + !file.exclusionRegExp.test(fileObj.leafName))) { + files.push(filePath); + } + } else if (fileObj.isDirectory() && + (!file.exclusionRegExp || !file.exclusionRegExp.test(fileObj.leafName))) { + dirFiles = this.getFilteredFileList(fileObj, regExpFilters, makeUnixPaths, true); + //Do not use push.apply for dir listings, can hit limit of max number + //of arguments to a function call, #921. + dirFiles.forEach(function (dirFile) { + files.push(dirFile); + }); + } + } + } + + return files; //Array + }, + + copyDir: function (/*String*/srcDir, /*String*/destDir, /*RegExp?*/regExpFilter, /*boolean?*/onlyCopyNew) { + //summary: copies files from srcDir to destDir using the regExpFilter to determine if the + //file should be copied. Returns a list file name strings of the destinations that were copied. + regExpFilter = regExpFilter || /\w/; + + var fileNames = file.getFilteredFileList(srcDir, regExpFilter, true), + copiedFiles = [], i, srcFileName, destFileName; + + for (i = 0; i < fileNames.length; i += 1) { + srcFileName = fileNames[i]; + destFileName = srcFileName.replace(srcDir, destDir); + + if (file.copyFile(srcFileName, destFileName, onlyCopyNew)) { + copiedFiles.push(destFileName); + } + } + + return copiedFiles.length ? copiedFiles : null; //Array or null + }, + + copyFile: function (/*String*/srcFileName, /*String*/destFileName, /*boolean?*/onlyCopyNew) { + //summary: copies srcFileName to destFileName. If onlyCopyNew is set, it only copies the file if + //srcFileName is newer than destFileName. Returns a boolean indicating if the copy occurred. + var destFile = xpfile(destFileName), + srcFile = xpfile(srcFileName); + + //logger.trace("Src filename: " + srcFileName); + //logger.trace("Dest filename: " + destFileName); + + //If onlyCopyNew is true, then compare dates and only copy if the src is newer + //than dest. + if (onlyCopyNew) { + if (destFile.exists() && destFile.lastModifiedTime >= srcFile.lastModifiedTime) { + return false; //Boolean + } + } + + srcFile.copyTo(destFile.parent, destFile.leafName); + + return true; //Boolean + }, + + /** + * Renames a file. May fail if "to" already exists or is on another drive. + */ + renameFile: function (from, to) { + var toFile = xpfile(to); + return xpfile(from).moveTo(toFile.parent, toFile.leafName); + }, + + readFile: xpcUtil.readFile, + + readFileAsync: function (path, encoding) { + var d = prim(); + try { + d.resolve(file.readFile(path, encoding)); + } catch (e) { + d.reject(e); + } + return d.promise; + }, + + saveUtf8File: function (/*String*/fileName, /*String*/fileContents) { + //summary: saves a file using UTF-8 encoding. + file.saveFile(fileName, fileContents, "utf-8"); + }, + + saveFile: function (/*String*/fileName, /*String*/fileContents, /*String?*/encoding) { + var outStream, convertStream, + fileObj = xpfile(fileName); + + mkFullDir(fileObj.parent); + + try { + outStream = Cc['@mozilla.org/network/file-output-stream;1'] + .createInstance(Ci.nsIFileOutputStream); + //438 is decimal for 0777 + outStream.init(fileObj, 0x02 | 0x08 | 0x20, 511, 0); + + convertStream = Cc['@mozilla.org/intl/converter-output-stream;1'] + .createInstance(Ci.nsIConverterOutputStream); + + convertStream.init(outStream, encoding, 0, 0); + convertStream.writeString(fileContents); + } catch (e) { + throw new Error((fileObj && fileObj.path || '') + ': ' + e); + } finally { + if (convertStream) { + convertStream.close(); + } + if (outStream) { + outStream.close(); + } + } + }, + + deleteFile: function (/*String*/fileName) { + //summary: deletes a file or directory if it exists. + var fileObj = xpfile(fileName); + if (fileObj.exists()) { + fileObj.remove(true); + } + }, + + /** + * Deletes any empty directories under the given directory. + * The startDirIsJavaObject is private to this implementation's + * recursion needs. + */ + deleteEmptyDirs: function (startDir, startDirIsObject) { + var topDir = startDir, + dirFileArray, fileObj; + + if (!startDirIsObject) { + topDir = xpfile(startDir); + } + + if (topDir.exists()) { + dirFileArray = topDir.directoryEntries; + while (dirFileArray.hasMoreElements()) { + fileObj = dirFileArray.getNext().QueryInterface(Ci.nsILocalFile); + + if (fileObj.isDirectory()) { + file.deleteEmptyDirs(fileObj, true); + } + } + + //If the directory is empty now, delete it. + dirFileArray = topDir.directoryEntries; + if (!dirFileArray.hasMoreElements()) { + file.deleteFile(topDir.path); + } + } + } + }; + + return file; +}); + +} + +if(env === 'browser') { +/*global process */ +define('browser/quit', function () { + 'use strict'; + return function (code) { + }; +}); +} + +if(env === 'node') { +/*global process */ +define('node/quit', function () { + 'use strict'; + return function (code) { + var draining = 0; + var exit = function () { + if (draining === 0) { + process.exit(code); + } else { + draining -= 1; + } + }; + if (process.stdout.bufferSize) { + draining += 1; + process.stdout.once('drain', exit); + } + if (process.stderr.bufferSize) { + draining += 1; + process.stderr.once('drain', exit); + } + exit(); + }; +}); + +} + +if(env === 'rhino') { +/*global quit */ +define('rhino/quit', function () { + 'use strict'; + return function (code) { + return quit(code); + }; +}); + +} + +if(env === 'xpconnect') { +/*global quit */ +define('xpconnect/quit', function () { + 'use strict'; + return function (code) { + return quit(code); + }; +}); + +} + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('browser/print', function () { + function print(msg) { + console.log(msg); + } + + return print; +}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false, console: false */ + +define('node/print', function () { + function print(msg) { + console.log(msg); + } + + return print; +}); + +} + +if(env === 'rhino') { +/*jslint strict: false */ +/*global define: false, print: false */ + +define('rhino/print', function () { + return print; +}); + +} + +if(env === 'xpconnect') { +/*jslint strict: false */ +/*global define: false, print: false */ + +define('xpconnect/print', function () { + return print; +}); + +} +/*jslint nomen: false, strict: false */ +/*global define: false */ + +define('logger', ['env!env/print'], function (print) { + var logger = { + TRACE: 0, + INFO: 1, + WARN: 2, + ERROR: 3, + SILENT: 4, + level: 0, + logPrefix: "", + + logLevel: function( level ) { + this.level = level; + }, + + trace: function (message) { + if (this.level <= this.TRACE) { + this._print(message); + } + }, + + info: function (message) { + if (this.level <= this.INFO) { + this._print(message); + } + }, + + warn: function (message) { + if (this.level <= this.WARN) { + this._print(message); + } + }, + + error: function (message) { + if (this.level <= this.ERROR) { + this._print(message); + } + }, + + _print: function (message) { + this._sysPrint((this.logPrefix ? (this.logPrefix + " ") : "") + message); + }, + + _sysPrint: function (message) { + print(message); + } + }; + + return logger; +}); +//Just a blank file to use when building the optimizer with the optimizer, +//so that the build does not attempt to inline some env modules, +//like Node's fs and path. + +(function webpackUniversalModuleDefinition(root, factory) { +/* istanbul ignore next */ + if(typeof define === 'function' && define.amd) + define('esprima', [], factory); +/* istanbul ignore next */ + else if(typeof exports === 'object') + exports["esprima"] = factory(); + else + root["esprima"] = factory(); +})(this, function() { +return /******/ (function(modules) { // webpackBootstrap +/******/ // The module cache +/******/ var installedModules = {}; + +/******/ // The require function +/******/ function __webpack_require__(moduleId) { + +/******/ // Check if module is in cache +/* istanbul ignore if */ +/******/ 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__) { + + "use strict"; + /* + Copyright JS Foundation and other contributors, https://js.foundation/ + + 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. + + 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 <COPYRIGHT HOLDER> 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. + */ + Object.defineProperty(exports, "__esModule", { value: true }); + var comment_handler_1 = __webpack_require__(1); + var jsx_parser_1 = __webpack_require__(3); + var parser_1 = __webpack_require__(8); + var tokenizer_1 = __webpack_require__(15); + function parse(code, options, delegate) { + var commentHandler = null; + var proxyDelegate = function (node, metadata) { + if (delegate) { + delegate(node, metadata); + } + if (commentHandler) { + commentHandler.visit(node, metadata); + } + }; + var parserDelegate = (typeof delegate === 'function') ? proxyDelegate : null; + var collectComment = false; + if (options) { + collectComment = (typeof options.comment === 'boolean' && options.comment); + var attachComment = (typeof options.attachComment === 'boolean' && options.attachComment); + if (collectComment || attachComment) { + commentHandler = new comment_handler_1.CommentHandler(); + commentHandler.attach = attachComment; + options.comment = true; + parserDelegate = proxyDelegate; + } + } + var isModule = false; + if (options && typeof options.sourceType === 'string') { + isModule = (options.sourceType === 'module'); + } + var parser; + if (options && typeof options.jsx === 'boolean' && options.jsx) { + parser = new jsx_parser_1.JSXParser(code, options, parserDelegate); + } + else { + parser = new parser_1.Parser(code, options, parserDelegate); + } + var program = isModule ? parser.parseModule() : parser.parseScript(); + var ast = program; + if (collectComment && commentHandler) { + ast.comments = commentHandler.comments; + } + if (parser.config.tokens) { + ast.tokens = parser.tokens; + } + if (parser.config.tolerant) { + ast.errors = parser.errorHandler.errors; + } + return ast; + } + exports.parse = parse; + function parseModule(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'module'; + return parse(code, parsingOptions, delegate); + } + exports.parseModule = parseModule; + function parseScript(code, options, delegate) { + var parsingOptions = options || {}; + parsingOptions.sourceType = 'script'; + return parse(code, parsingOptions, delegate); + } + exports.parseScript = parseScript; + function tokenize(code, options, delegate) { + var tokenizer = new tokenizer_1.Tokenizer(code, options); + var tokens; + tokens = []; + try { + while (true) { + var token = tokenizer.getNextToken(); + if (!token) { + break; + } + if (delegate) { + token = delegate(token); + } + tokens.push(token); + } + } + catch (e) { + tokenizer.errorHandler.tolerate(e); + } + if (tokenizer.errorHandler.tolerant) { + tokens.errors = tokenizer.errors(); + } + return tokens; + } + exports.tokenize = tokenize; + var syntax_1 = __webpack_require__(2); + exports.Syntax = syntax_1.Syntax; + // Sync with *.json manifests. + exports.version = '4.0.0'; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + var CommentHandler = (function () { + function CommentHandler() { + this.attach = false; + this.comments = []; + this.stack = []; + this.leading = []; + this.trailing = []; + } + CommentHandler.prototype.insertInnerComments = function (node, metadata) { + // innnerComments for properties empty block + // `function a() {/** comments **\/}` + if (node.type === syntax_1.Syntax.BlockStatement && node.body.length === 0) { + var innerComments = []; + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (metadata.end.offset >= entry.start) { + innerComments.unshift(entry.comment); + this.leading.splice(i, 1); + this.trailing.splice(i, 1); + } + } + if (innerComments.length) { + node.innerComments = innerComments; + } + } + }; + CommentHandler.prototype.findTrailingComments = function (metadata) { + var trailingComments = []; + if (this.trailing.length > 0) { + for (var i = this.trailing.length - 1; i >= 0; --i) { + var entry_1 = this.trailing[i]; + if (entry_1.start >= metadata.end.offset) { + trailingComments.unshift(entry_1.comment); + } + } + this.trailing.length = 0; + return trailingComments; + } + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.node.trailingComments) { + var firstComment = entry.node.trailingComments[0]; + if (firstComment && firstComment.range[0] >= metadata.end.offset) { + trailingComments = entry.node.trailingComments; + delete entry.node.trailingComments; + } + } + return trailingComments; + }; + CommentHandler.prototype.findLeadingComments = function (metadata) { + var leadingComments = []; + var target; + while (this.stack.length > 0) { + var entry = this.stack[this.stack.length - 1]; + if (entry && entry.start >= metadata.start.offset) { + target = entry.node; + this.stack.pop(); + } + else { + break; + } + } + if (target) { + var count = target.leadingComments ? target.leadingComments.length : 0; + for (var i = count - 1; i >= 0; --i) { + var comment = target.leadingComments[i]; + if (comment.range[1] <= metadata.start.offset) { + leadingComments.unshift(comment); + target.leadingComments.splice(i, 1); + } + } + if (target.leadingComments && target.leadingComments.length === 0) { + delete target.leadingComments; + } + return leadingComments; + } + for (var i = this.leading.length - 1; i >= 0; --i) { + var entry = this.leading[i]; + if (entry.start <= metadata.start.offset) { + leadingComments.unshift(entry.comment); + this.leading.splice(i, 1); + } + } + return leadingComments; + }; + CommentHandler.prototype.visitNode = function (node, metadata) { + if (node.type === syntax_1.Syntax.Program && node.body.length > 0) { + return; + } + this.insertInnerComments(node, metadata); + var trailingComments = this.findTrailingComments(metadata); + var leadingComments = this.findLeadingComments(metadata); + if (leadingComments.length > 0) { + node.leadingComments = leadingComments; + } + if (trailingComments.length > 0) { + node.trailingComments = trailingComments; + } + this.stack.push({ + node: node, + start: metadata.start.offset + }); + }; + CommentHandler.prototype.visitComment = function (node, metadata) { + var type = (node.type[0] === 'L') ? 'Line' : 'Block'; + var comment = { + type: type, + value: node.value + }; + if (node.range) { + comment.range = node.range; + } + if (node.loc) { + comment.loc = node.loc; + } + this.comments.push(comment); + if (this.attach) { + var entry = { + comment: { + type: type, + value: node.value, + range: [metadata.start.offset, metadata.end.offset] + }, + start: metadata.start.offset + }; + if (node.loc) { + entry.comment.loc = node.loc; + } + node.type = type; + this.leading.push(entry); + this.trailing.push(entry); + } + }; + CommentHandler.prototype.visit = function (node, metadata) { + if (node.type === 'LineComment') { + this.visitComment(node, metadata); + } + else if (node.type === 'BlockComment') { + this.visitComment(node, metadata); + } + else if (this.attach) { + this.visitNode(node, metadata); + } + }; + return CommentHandler; + }()); + exports.CommentHandler = CommentHandler; + + +/***/ }, +/* 2 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Syntax = { + AssignmentExpression: 'AssignmentExpression', + AssignmentPattern: 'AssignmentPattern', + ArrayExpression: 'ArrayExpression', + ArrayPattern: 'ArrayPattern', + ArrowFunctionExpression: 'ArrowFunctionExpression', + AwaitExpression: 'AwaitExpression', + BlockStatement: 'BlockStatement', + BinaryExpression: 'BinaryExpression', + BreakStatement: 'BreakStatement', + CallExpression: 'CallExpression', + CatchClause: 'CatchClause', + ClassBody: 'ClassBody', + ClassDeclaration: 'ClassDeclaration', + ClassExpression: 'ClassExpression', + ConditionalExpression: 'ConditionalExpression', + ContinueStatement: 'ContinueStatement', + DoWhileStatement: 'DoWhileStatement', + DebuggerStatement: 'DebuggerStatement', + EmptyStatement: 'EmptyStatement', + ExportAllDeclaration: 'ExportAllDeclaration', + ExportDefaultDeclaration: 'ExportDefaultDeclaration', + ExportNamedDeclaration: 'ExportNamedDeclaration', + ExportSpecifier: 'ExportSpecifier', + ExpressionStatement: 'ExpressionStatement', + ForStatement: 'ForStatement', + ForOfStatement: 'ForOfStatement', + ForInStatement: 'ForInStatement', + FunctionDeclaration: 'FunctionDeclaration', + FunctionExpression: 'FunctionExpression', + Identifier: 'Identifier', + IfStatement: 'IfStatement', + ImportDeclaration: 'ImportDeclaration', + ImportDefaultSpecifier: 'ImportDefaultSpecifier', + ImportNamespaceSpecifier: 'ImportNamespaceSpecifier', + ImportSpecifier: 'ImportSpecifier', + Literal: 'Literal', + LabeledStatement: 'LabeledStatement', + LogicalExpression: 'LogicalExpression', + MemberExpression: 'MemberExpression', + MetaProperty: 'MetaProperty', + MethodDefinition: 'MethodDefinition', + NewExpression: 'NewExpression', + ObjectExpression: 'ObjectExpression', + ObjectPattern: 'ObjectPattern', + Program: 'Program', + Property: 'Property', + RestElement: 'RestElement', + ReturnStatement: 'ReturnStatement', + SequenceExpression: 'SequenceExpression', + SpreadElement: 'SpreadElement', + Super: 'Super', + SwitchCase: 'SwitchCase', + SwitchStatement: 'SwitchStatement', + TaggedTemplateExpression: 'TaggedTemplateExpression', + TemplateElement: 'TemplateElement', + TemplateLiteral: 'TemplateLiteral', + ThisExpression: 'ThisExpression', + ThrowStatement: 'ThrowStatement', + TryStatement: 'TryStatement', + UnaryExpression: 'UnaryExpression', + UpdateExpression: 'UpdateExpression', + VariableDeclaration: 'VariableDeclaration', + VariableDeclarator: 'VariableDeclarator', + WhileStatement: 'WhileStatement', + WithStatement: 'WithStatement', + YieldExpression: 'YieldExpression' + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; +/* istanbul ignore next */ + var __extends = (this && this.__extends) || (function () { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; + return function (d, b) { + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + })(); + Object.defineProperty(exports, "__esModule", { value: true }); + var character_1 = __webpack_require__(4); + var JSXNode = __webpack_require__(5); + var jsx_syntax_1 = __webpack_require__(6); + var Node = __webpack_require__(7); + var parser_1 = __webpack_require__(8); + var token_1 = __webpack_require__(13); + var xhtml_entities_1 = __webpack_require__(14); + token_1.TokenName[100 /* Identifier */] = 'JSXIdentifier'; + token_1.TokenName[101 /* Text */] = 'JSXText'; + // Fully qualified element name, e.g. <svg:path> returns "svg:path" + function getQualifiedElementName(elementName) { + var qualifiedName; + switch (elementName.type) { + case jsx_syntax_1.JSXSyntax.JSXIdentifier: + var id = elementName; + qualifiedName = id.name; + break; + case jsx_syntax_1.JSXSyntax.JSXNamespacedName: + var ns = elementName; + qualifiedName = getQualifiedElementName(ns.namespace) + ':' + + getQualifiedElementName(ns.name); + break; + case jsx_syntax_1.JSXSyntax.JSXMemberExpression: + var expr = elementName; + qualifiedName = getQualifiedElementName(expr.object) + '.' + + getQualifiedElementName(expr.property); + break; + /* istanbul ignore next */ + default: + break; + } + return qualifiedName; + } + var JSXParser = (function (_super) { + __extends(JSXParser, _super); + function JSXParser(code, options, delegate) { + return _super.call(this, code, options, delegate) || this; + } + JSXParser.prototype.parsePrimaryExpression = function () { + return this.match('<') ? this.parseJSXRoot() : _super.prototype.parsePrimaryExpression.call(this); + }; + JSXParser.prototype.startJSX = function () { + // Unwind the scanner before the lookahead token. + this.scanner.index = this.startMarker.index; + this.scanner.lineNumber = this.startMarker.line; + this.scanner.lineStart = this.startMarker.index - this.startMarker.column; + }; + JSXParser.prototype.finishJSX = function () { + // Prime the next lookahead. + this.nextToken(); + }; + JSXParser.prototype.reenterJSX = function () { + this.startJSX(); + this.expectJSX('}'); + // Pop the closing '}' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + }; + JSXParser.prototype.createJSXNode = function () { + this.collectComments(); + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.createJSXChildNode = function () { + return { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + }; + JSXParser.prototype.scanXHTMLEntity = function (quote) { + var result = '&'; + var valid = true; + var terminated = false; + var numeric = false; + var hex = false; + while (!this.scanner.eof() && valid && !terminated) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === quote) { + break; + } + terminated = (ch === ';'); + result += ch; + ++this.scanner.index; + if (!terminated) { + switch (result.length) { + case 2: + // e.g. '{' + numeric = (ch === '#'); + break; + case 3: + if (numeric) { + // e.g. 'A' + hex = (ch === 'x'); + valid = hex || character_1.Character.isDecimalDigit(ch.charCodeAt(0)); + numeric = numeric && !hex; + } + break; + default: + valid = valid && !(numeric && !character_1.Character.isDecimalDigit(ch.charCodeAt(0))); + valid = valid && !(hex && !character_1.Character.isHexDigit(ch.charCodeAt(0))); + break; + } + } + } + if (valid && terminated && result.length > 2) { + // e.g. 'A' becomes just '#x41' + var str = result.substr(1, result.length - 2); + if (numeric && str.length > 1) { + result = String.fromCharCode(parseInt(str.substr(1), 10)); + } + else if (hex && str.length > 2) { + result = String.fromCharCode(parseInt('0' + str.substr(1), 16)); + } + else if (!numeric && !hex && xhtml_entities_1.XHTMLEntities[str]) { + result = xhtml_entities_1.XHTMLEntities[str]; + } + } + return result; + }; + // Scan the next JSX token. This replaces Scanner#lex when in JSX mode. + JSXParser.prototype.lexJSX = function () { + var cp = this.scanner.source.charCodeAt(this.scanner.index); + // < > / : = { } + if (cp === 60 || cp === 62 || cp === 47 || cp === 58 || cp === 61 || cp === 123 || cp === 125) { + var value = this.scanner.source[this.scanner.index++]; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index - 1, + end: this.scanner.index + }; + } + // " ' + if (cp === 34 || cp === 39) { + var start = this.scanner.index; + var quote = this.scanner.source[this.scanner.index++]; + var str = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index++]; + if (ch === quote) { + break; + } + else if (ch === '&') { + str += this.scanXHTMLEntity(quote); + } + else { + str += ch; + } + } + return { + type: 8 /* StringLiteral */, + value: str, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ... or . + if (cp === 46) { + var n1 = this.scanner.source.charCodeAt(this.scanner.index + 1); + var n2 = this.scanner.source.charCodeAt(this.scanner.index + 2); + var value = (n1 === 46 && n2 === 46) ? '...' : '.'; + var start = this.scanner.index; + this.scanner.index += value.length; + return { + type: 7 /* Punctuator */, + value: value, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + // ` + if (cp === 96) { + // Only placeholder, since it will be rescanned as a real assignment expression. + return { + type: 10 /* Template */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: this.scanner.index, + end: this.scanner.index + }; + } + // Identifer can not contain backslash (char code 92). + if (character_1.Character.isIdentifierStart(cp) && (cp !== 92)) { + var start = this.scanner.index; + ++this.scanner.index; + while (!this.scanner.eof()) { + var ch = this.scanner.source.charCodeAt(this.scanner.index); + if (character_1.Character.isIdentifierPart(ch) && (ch !== 92)) { + ++this.scanner.index; + } + else if (ch === 45) { + // Hyphen (char code 45) can be part of an identifier. + ++this.scanner.index; + } + else { + break; + } + } + var id = this.scanner.source.slice(start, this.scanner.index); + return { + type: 100 /* Identifier */, + value: id, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + } + return this.scanner.lex(); + }; + JSXParser.prototype.nextJSXToken = function () { + this.collectComments(); + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var token = this.lexJSX(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + if (this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.nextJSXText = function () { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + var start = this.scanner.index; + var text = ''; + while (!this.scanner.eof()) { + var ch = this.scanner.source[this.scanner.index]; + if (ch === '{' || ch === '<') { + break; + } + ++this.scanner.index; + text += ch; + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.scanner.lineNumber; + if (ch === '\r' && this.scanner.source[this.scanner.index] === '\n') { + ++this.scanner.index; + } + this.scanner.lineStart = this.scanner.index; + } + } + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + var token = { + type: 101 /* Text */, + value: text, + lineNumber: this.scanner.lineNumber, + lineStart: this.scanner.lineStart, + start: start, + end: this.scanner.index + }; + if ((text.length > 0) && this.config.tokens) { + this.tokens.push(this.convertToken(token)); + } + return token; + }; + JSXParser.prototype.peekJSXToken = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.lexJSX(); + this.scanner.restoreState(state); + return next; + }; + // Expect the next JSX token to match the specified punctuator. + // If not, an exception will be thrown. + JSXParser.prototype.expectJSX = function (value) { + var token = this.nextJSXToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next JSX token matches the specified punctuator. + JSXParser.prototype.matchJSX = function (value) { + var next = this.peekJSXToken(); + return next.type === 7 /* Punctuator */ && next.value === value; + }; + JSXParser.prototype.parseJSXIdentifier = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 100 /* Identifier */) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new JSXNode.JSXIdentifier(token.value)); + }; + JSXParser.prototype.parseJSXElementName = function () { + var node = this.createJSXNode(); + var elementName = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = elementName; + this.expectJSX(':'); + var name_1 = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_1)); + } + else if (this.matchJSX('.')) { + while (this.matchJSX('.')) { + var object = elementName; + this.expectJSX('.'); + var property = this.parseJSXIdentifier(); + elementName = this.finalize(node, new JSXNode.JSXMemberExpression(object, property)); + } + } + return elementName; + }; + JSXParser.prototype.parseJSXAttributeName = function () { + var node = this.createJSXNode(); + var attributeName; + var identifier = this.parseJSXIdentifier(); + if (this.matchJSX(':')) { + var namespace = identifier; + this.expectJSX(':'); + var name_2 = this.parseJSXIdentifier(); + attributeName = this.finalize(node, new JSXNode.JSXNamespacedName(namespace, name_2)); + } + else { + attributeName = identifier; + } + return attributeName; + }; + JSXParser.prototype.parseJSXStringLiteralAttribute = function () { + var node = this.createJSXNode(); + var token = this.nextJSXToken(); + if (token.type !== 8 /* StringLiteral */) { + this.throwUnexpectedToken(token); + } + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + JSXParser.prototype.parseJSXExpressionAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.finishJSX(); + if (this.match('}')) { + this.tolerateError('JSX attributes must only be assigned a non-empty expression'); + } + var expression = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXAttributeValue = function () { + return this.matchJSX('{') ? this.parseJSXExpressionAttribute() : + this.matchJSX('<') ? this.parseJSXElement() : this.parseJSXStringLiteralAttribute(); + }; + JSXParser.prototype.parseJSXNameValueAttribute = function () { + var node = this.createJSXNode(); + var name = this.parseJSXAttributeName(); + var value = null; + if (this.matchJSX('=')) { + this.expectJSX('='); + value = this.parseJSXAttributeValue(); + } + return this.finalize(node, new JSXNode.JSXAttribute(name, value)); + }; + JSXParser.prototype.parseJSXSpreadAttribute = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + this.expectJSX('...'); + this.finishJSX(); + var argument = this.parseAssignmentExpression(); + this.reenterJSX(); + return this.finalize(node, new JSXNode.JSXSpreadAttribute(argument)); + }; + JSXParser.prototype.parseJSXAttributes = function () { + var attributes = []; + while (!this.matchJSX('/') && !this.matchJSX('>')) { + var attribute = this.matchJSX('{') ? this.parseJSXSpreadAttribute() : + this.parseJSXNameValueAttribute(); + attributes.push(attribute); + } + return attributes; + }; + JSXParser.prototype.parseJSXOpeningElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXBoundaryElement = function () { + var node = this.createJSXNode(); + this.expectJSX('<'); + if (this.matchJSX('/')) { + this.expectJSX('/'); + var name_3 = this.parseJSXElementName(); + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXClosingElement(name_3)); + } + var name = this.parseJSXElementName(); + var attributes = this.parseJSXAttributes(); + var selfClosing = this.matchJSX('/'); + if (selfClosing) { + this.expectJSX('/'); + } + this.expectJSX('>'); + return this.finalize(node, new JSXNode.JSXOpeningElement(name, selfClosing, attributes)); + }; + JSXParser.prototype.parseJSXEmptyExpression = function () { + var node = this.createJSXChildNode(); + this.collectComments(); + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + return this.finalize(node, new JSXNode.JSXEmptyExpression()); + }; + JSXParser.prototype.parseJSXExpressionContainer = function () { + var node = this.createJSXNode(); + this.expectJSX('{'); + var expression; + if (this.matchJSX('}')) { + expression = this.parseJSXEmptyExpression(); + this.expectJSX('}'); + } + else { + this.finishJSX(); + expression = this.parseAssignmentExpression(); + this.reenterJSX(); + } + return this.finalize(node, new JSXNode.JSXExpressionContainer(expression)); + }; + JSXParser.prototype.parseJSXChildren = function () { + var children = []; + while (!this.scanner.eof()) { + var node = this.createJSXChildNode(); + var token = this.nextJSXText(); + if (token.start < token.end) { + var raw = this.getTokenRaw(token); + var child = this.finalize(node, new JSXNode.JSXText(token.value, raw)); + children.push(child); + } + if (this.scanner.source[this.scanner.index] === '{') { + var container = this.parseJSXExpressionContainer(); + children.push(container); + } + else { + break; + } + } + return children; + }; + JSXParser.prototype.parseComplexJSXElement = function (el) { + var stack = []; + while (!this.scanner.eof()) { + el.children = el.children.concat(this.parseJSXChildren()); + var node = this.createJSXChildNode(); + var element = this.parseJSXBoundaryElement(); + if (element.type === jsx_syntax_1.JSXSyntax.JSXOpeningElement) { + var opening = element; + if (opening.selfClosing) { + var child = this.finalize(node, new JSXNode.JSXElement(opening, [], null)); + el.children.push(child); + } + else { + stack.push(el); + el = { node: node, opening: opening, closing: null, children: [] }; + } + } + if (element.type === jsx_syntax_1.JSXSyntax.JSXClosingElement) { + el.closing = element; + var open_1 = getQualifiedElementName(el.opening.name); + var close_1 = getQualifiedElementName(el.closing.name); + if (open_1 !== close_1) { + this.tolerateError('Expected corresponding JSX closing tag for %0', open_1); + } + if (stack.length > 0) { + var child = this.finalize(el.node, new JSXNode.JSXElement(el.opening, el.children, el.closing)); + el = stack[stack.length - 1]; + el.children.push(child); + stack.pop(); + } + else { + break; + } + } + } + return el; + }; + JSXParser.prototype.parseJSXElement = function () { + var node = this.createJSXNode(); + var opening = this.parseJSXOpeningElement(); + var children = []; + var closing = null; + if (!opening.selfClosing) { + var el = this.parseComplexJSXElement({ node: node, opening: opening, closing: closing, children: children }); + children = el.children; + closing = el.closing; + } + return this.finalize(node, new JSXNode.JSXElement(opening, children, closing)); + }; + JSXParser.prototype.parseJSXRoot = function () { + // Pop the opening '<' added from the lookahead. + if (this.config.tokens) { + this.tokens.pop(); + } + this.startJSX(); + var element = this.parseJSXElement(); + this.finishJSX(); + return element; + }; + JSXParser.prototype.isStartOfExpression = function () { + return _super.prototype.isStartOfExpression.call(this) || this.match('<'); + }; + return JSXParser; + }(parser_1.Parser)); + exports.JSXParser = JSXParser; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // See also tools/generate-unicode-regex.js. + var Regex = { + // Unicode v8.0.0 NonAsciiIdentifierStart: + NonAsciiIdentifierStart: /[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B4\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0AF9\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58-\u0C5A\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D5F-\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA8FD\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE2B\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF50\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDDD8-\uDDDB\uDE00-\uDE2F\uDE44\uDE80-\uDEAA\uDF00-\uDF19]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]/, + // Unicode v8.0.0 NonAsciiIdentifierPart: + NonAsciiIdentifierPart: /[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B4\u08E3-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0AF9\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58-\u0C5A\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D5F-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F5\u13F8-\u13FD\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FD5\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA7AD\uA7B0-\uA7B7\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA8FD\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB65\uAB70-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2F\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDCE0-\uDCF2\uDCF4\uDCF5\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48\uDC80-\uDCB2\uDCC0-\uDCF2]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDCA-\uDDCC\uDDD0-\uDDDA\uDDDC\uDE00-\uDE11\uDE13-\uDE37\uDE80-\uDE86\uDE88\uDE8A-\uDE8D\uDE8F-\uDE9D\uDE9F-\uDEA8\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF00-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF50\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDDD8-\uDDDD\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9\uDF00-\uDF19\uDF1D-\uDF2B\uDF30-\uDF39]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF99]|\uD809[\uDC00-\uDC6E\uDC80-\uDD43]|[\uD80C\uD840-\uD868\uD86A-\uD86C\uD86F-\uD872][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD811[\uDC00-\uDE46]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD836[\uDE00-\uDE36\uDE3B-\uDE6C\uDE75\uDE84\uDE9B-\uDE9F\uDEA1-\uDEAF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D\uDC20-\uDFFF]|\uD873[\uDC00-\uDEA1]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/ + }; + exports.Character = { + /* tslint:disable:no-bitwise */ + fromCodePoint: function (cp) { + return (cp < 0x10000) ? String.fromCharCode(cp) : + String.fromCharCode(0xD800 + ((cp - 0x10000) >> 10)) + + String.fromCharCode(0xDC00 + ((cp - 0x10000) & 1023)); + }, + // https://tc39.github.io/ecma262/#sec-white-space + isWhiteSpace: function (cp) { + return (cp === 0x20) || (cp === 0x09) || (cp === 0x0B) || (cp === 0x0C) || (cp === 0xA0) || + (cp >= 0x1680 && [0x1680, 0x2000, 0x2001, 0x2002, 0x2003, 0x2004, 0x2005, 0x2006, 0x2007, 0x2008, 0x2009, 0x200A, 0x202F, 0x205F, 0x3000, 0xFEFF].indexOf(cp) >= 0); + }, + // https://tc39.github.io/ecma262/#sec-line-terminators + isLineTerminator: function (cp) { + return (cp === 0x0A) || (cp === 0x0D) || (cp === 0x2028) || (cp === 0x2029); + }, + // https://tc39.github.io/ecma262/#sec-names-and-keywords + isIdentifierStart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierStart.test(exports.Character.fromCodePoint(cp))); + }, + isIdentifierPart: function (cp) { + return (cp === 0x24) || (cp === 0x5F) || + (cp >= 0x41 && cp <= 0x5A) || + (cp >= 0x61 && cp <= 0x7A) || + (cp >= 0x30 && cp <= 0x39) || + (cp === 0x5C) || + ((cp >= 0x80) && Regex.NonAsciiIdentifierPart.test(exports.Character.fromCodePoint(cp))); + }, + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + isDecimalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39); // 0..9 + }, + isHexDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x39) || + (cp >= 0x41 && cp <= 0x46) || + (cp >= 0x61 && cp <= 0x66); // a..f + }, + isOctalDigit: function (cp) { + return (cp >= 0x30 && cp <= 0x37); // 0..7 + } + }; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var jsx_syntax_1 = __webpack_require__(6); + /* tslint:disable:max-classes-per-file */ + var JSXClosingElement = (function () { + function JSXClosingElement(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXClosingElement; + this.name = name; + } + return JSXClosingElement; + }()); + exports.JSXClosingElement = JSXClosingElement; + var JSXElement = (function () { + function JSXElement(openingElement, children, closingElement) { + this.type = jsx_syntax_1.JSXSyntax.JSXElement; + this.openingElement = openingElement; + this.children = children; + this.closingElement = closingElement; + } + return JSXElement; + }()); + exports.JSXElement = JSXElement; + var JSXEmptyExpression = (function () { + function JSXEmptyExpression() { + this.type = jsx_syntax_1.JSXSyntax.JSXEmptyExpression; + } + return JSXEmptyExpression; + }()); + exports.JSXEmptyExpression = JSXEmptyExpression; + var JSXExpressionContainer = (function () { + function JSXExpressionContainer(expression) { + this.type = jsx_syntax_1.JSXSyntax.JSXExpressionContainer; + this.expression = expression; + } + return JSXExpressionContainer; + }()); + exports.JSXExpressionContainer = JSXExpressionContainer; + var JSXIdentifier = (function () { + function JSXIdentifier(name) { + this.type = jsx_syntax_1.JSXSyntax.JSXIdentifier; + this.name = name; + } + return JSXIdentifier; + }()); + exports.JSXIdentifier = JSXIdentifier; + var JSXMemberExpression = (function () { + function JSXMemberExpression(object, property) { + this.type = jsx_syntax_1.JSXSyntax.JSXMemberExpression; + this.object = object; + this.property = property; + } + return JSXMemberExpression; + }()); + exports.JSXMemberExpression = JSXMemberExpression; + var JSXAttribute = (function () { + function JSXAttribute(name, value) { + this.type = jsx_syntax_1.JSXSyntax.JSXAttribute; + this.name = name; + this.value = value; + } + return JSXAttribute; + }()); + exports.JSXAttribute = JSXAttribute; + var JSXNamespacedName = (function () { + function JSXNamespacedName(namespace, name) { + this.type = jsx_syntax_1.JSXSyntax.JSXNamespacedName; + this.namespace = namespace; + this.name = name; + } + return JSXNamespacedName; + }()); + exports.JSXNamespacedName = JSXNamespacedName; + var JSXOpeningElement = (function () { + function JSXOpeningElement(name, selfClosing, attributes) { + this.type = jsx_syntax_1.JSXSyntax.JSXOpeningElement; + this.name = name; + this.selfClosing = selfClosing; + this.attributes = attributes; + } + return JSXOpeningElement; + }()); + exports.JSXOpeningElement = JSXOpeningElement; + var JSXSpreadAttribute = (function () { + function JSXSpreadAttribute(argument) { + this.type = jsx_syntax_1.JSXSyntax.JSXSpreadAttribute; + this.argument = argument; + } + return JSXSpreadAttribute; + }()); + exports.JSXSpreadAttribute = JSXSpreadAttribute; + var JSXText = (function () { + function JSXText(value, raw) { + this.type = jsx_syntax_1.JSXSyntax.JSXText; + this.value = value; + this.raw = raw; + } + return JSXText; + }()); + exports.JSXText = JSXText; + + +/***/ }, +/* 6 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JSXSyntax = { + JSXAttribute: 'JSXAttribute', + JSXClosingElement: 'JSXClosingElement', + JSXElement: 'JSXElement', + JSXEmptyExpression: 'JSXEmptyExpression', + JSXExpressionContainer: 'JSXExpressionContainer', + JSXIdentifier: 'JSXIdentifier', + JSXMemberExpression: 'JSXMemberExpression', + JSXNamespacedName: 'JSXNamespacedName', + JSXOpeningElement: 'JSXOpeningElement', + JSXSpreadAttribute: 'JSXSpreadAttribute', + JSXText: 'JSXText' + }; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var syntax_1 = __webpack_require__(2); + /* tslint:disable:max-classes-per-file */ + var ArrayExpression = (function () { + function ArrayExpression(elements) { + this.type = syntax_1.Syntax.ArrayExpression; + this.elements = elements; + } + return ArrayExpression; + }()); + exports.ArrayExpression = ArrayExpression; + var ArrayPattern = (function () { + function ArrayPattern(elements) { + this.type = syntax_1.Syntax.ArrayPattern; + this.elements = elements; + } + return ArrayPattern; + }()); + exports.ArrayPattern = ArrayPattern; + var ArrowFunctionExpression = (function () { + function ArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = false; + } + return ArrowFunctionExpression; + }()); + exports.ArrowFunctionExpression = ArrowFunctionExpression; + var AssignmentExpression = (function () { + function AssignmentExpression(operator, left, right) { + this.type = syntax_1.Syntax.AssignmentExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return AssignmentExpression; + }()); + exports.AssignmentExpression = AssignmentExpression; + var AssignmentPattern = (function () { + function AssignmentPattern(left, right) { + this.type = syntax_1.Syntax.AssignmentPattern; + this.left = left; + this.right = right; + } + return AssignmentPattern; + }()); + exports.AssignmentPattern = AssignmentPattern; + var AsyncArrowFunctionExpression = (function () { + function AsyncArrowFunctionExpression(params, body, expression) { + this.type = syntax_1.Syntax.ArrowFunctionExpression; + this.id = null; + this.params = params; + this.body = body; + this.generator = false; + this.expression = expression; + this.async = true; + } + return AsyncArrowFunctionExpression; + }()); + exports.AsyncArrowFunctionExpression = AsyncArrowFunctionExpression; + var AsyncFunctionDeclaration = (function () { + function AsyncFunctionDeclaration(id, params, body) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionDeclaration; + }()); + exports.AsyncFunctionDeclaration = AsyncFunctionDeclaration; + var AsyncFunctionExpression = (function () { + function AsyncFunctionExpression(id, params, body) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = false; + this.expression = false; + this.async = true; + } + return AsyncFunctionExpression; + }()); + exports.AsyncFunctionExpression = AsyncFunctionExpression; + var AwaitExpression = (function () { + function AwaitExpression(argument) { + this.type = syntax_1.Syntax.AwaitExpression; + this.argument = argument; + } + return AwaitExpression; + }()); + exports.AwaitExpression = AwaitExpression; + var BinaryExpression = (function () { + function BinaryExpression(operator, left, right) { + var logical = (operator === '||' || operator === '&&'); + this.type = logical ? syntax_1.Syntax.LogicalExpression : syntax_1.Syntax.BinaryExpression; + this.operator = operator; + this.left = left; + this.right = right; + } + return BinaryExpression; + }()); + exports.BinaryExpression = BinaryExpression; + var BlockStatement = (function () { + function BlockStatement(body) { + this.type = syntax_1.Syntax.BlockStatement; + this.body = body; + } + return BlockStatement; + }()); + exports.BlockStatement = BlockStatement; + var BreakStatement = (function () { + function BreakStatement(label) { + this.type = syntax_1.Syntax.BreakStatement; + this.label = label; + } + return BreakStatement; + }()); + exports.BreakStatement = BreakStatement; + var CallExpression = (function () { + function CallExpression(callee, args) { + this.type = syntax_1.Syntax.CallExpression; + this.callee = callee; + this.arguments = args; + } + return CallExpression; + }()); + exports.CallExpression = CallExpression; + var CatchClause = (function () { + function CatchClause(param, body) { + this.type = syntax_1.Syntax.CatchClause; + this.param = param; + this.body = body; + } + return CatchClause; + }()); + exports.CatchClause = CatchClause; + var ClassBody = (function () { + function ClassBody(body) { + this.type = syntax_1.Syntax.ClassBody; + this.body = body; + } + return ClassBody; + }()); + exports.ClassBody = ClassBody; + var ClassDeclaration = (function () { + function ClassDeclaration(id, superClass, body) { + this.type = syntax_1.Syntax.ClassDeclaration; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassDeclaration; + }()); + exports.ClassDeclaration = ClassDeclaration; + var ClassExpression = (function () { + function ClassExpression(id, superClass, body) { + this.type = syntax_1.Syntax.ClassExpression; + this.id = id; + this.superClass = superClass; + this.body = body; + } + return ClassExpression; + }()); + exports.ClassExpression = ClassExpression; + var ComputedMemberExpression = (function () { + function ComputedMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = true; + this.object = object; + this.property = property; + } + return ComputedMemberExpression; + }()); + exports.ComputedMemberExpression = ComputedMemberExpression; + var ConditionalExpression = (function () { + function ConditionalExpression(test, consequent, alternate) { + this.type = syntax_1.Syntax.ConditionalExpression; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return ConditionalExpression; + }()); + exports.ConditionalExpression = ConditionalExpression; + var ContinueStatement = (function () { + function ContinueStatement(label) { + this.type = syntax_1.Syntax.ContinueStatement; + this.label = label; + } + return ContinueStatement; + }()); + exports.ContinueStatement = ContinueStatement; + var DebuggerStatement = (function () { + function DebuggerStatement() { + this.type = syntax_1.Syntax.DebuggerStatement; + } + return DebuggerStatement; + }()); + exports.DebuggerStatement = DebuggerStatement; + var Directive = (function () { + function Directive(expression, directive) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + this.directive = directive; + } + return Directive; + }()); + exports.Directive = Directive; + var DoWhileStatement = (function () { + function DoWhileStatement(body, test) { + this.type = syntax_1.Syntax.DoWhileStatement; + this.body = body; + this.test = test; + } + return DoWhileStatement; + }()); + exports.DoWhileStatement = DoWhileStatement; + var EmptyStatement = (function () { + function EmptyStatement() { + this.type = syntax_1.Syntax.EmptyStatement; + } + return EmptyStatement; + }()); + exports.EmptyStatement = EmptyStatement; + var ExportAllDeclaration = (function () { + function ExportAllDeclaration(source) { + this.type = syntax_1.Syntax.ExportAllDeclaration; + this.source = source; + } + return ExportAllDeclaration; + }()); + exports.ExportAllDeclaration = ExportAllDeclaration; + var ExportDefaultDeclaration = (function () { + function ExportDefaultDeclaration(declaration) { + this.type = syntax_1.Syntax.ExportDefaultDeclaration; + this.declaration = declaration; + } + return ExportDefaultDeclaration; + }()); + exports.ExportDefaultDeclaration = ExportDefaultDeclaration; + var ExportNamedDeclaration = (function () { + function ExportNamedDeclaration(declaration, specifiers, source) { + this.type = syntax_1.Syntax.ExportNamedDeclaration; + this.declaration = declaration; + this.specifiers = specifiers; + this.source = source; + } + return ExportNamedDeclaration; + }()); + exports.ExportNamedDeclaration = ExportNamedDeclaration; + var ExportSpecifier = (function () { + function ExportSpecifier(local, exported) { + this.type = syntax_1.Syntax.ExportSpecifier; + this.exported = exported; + this.local = local; + } + return ExportSpecifier; + }()); + exports.ExportSpecifier = ExportSpecifier; + var ExpressionStatement = (function () { + function ExpressionStatement(expression) { + this.type = syntax_1.Syntax.ExpressionStatement; + this.expression = expression; + } + return ExpressionStatement; + }()); + exports.ExpressionStatement = ExpressionStatement; + var ForInStatement = (function () { + function ForInStatement(left, right, body) { + this.type = syntax_1.Syntax.ForInStatement; + this.left = left; + this.right = right; + this.body = body; + this.each = false; + } + return ForInStatement; + }()); + exports.ForInStatement = ForInStatement; + var ForOfStatement = (function () { + function ForOfStatement(left, right, body) { + this.type = syntax_1.Syntax.ForOfStatement; + this.left = left; + this.right = right; + this.body = body; + } + return ForOfStatement; + }()); + exports.ForOfStatement = ForOfStatement; + var ForStatement = (function () { + function ForStatement(init, test, update, body) { + this.type = syntax_1.Syntax.ForStatement; + this.init = init; + this.test = test; + this.update = update; + this.body = body; + } + return ForStatement; + }()); + exports.ForStatement = ForStatement; + var FunctionDeclaration = (function () { + function FunctionDeclaration(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionDeclaration; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionDeclaration; + }()); + exports.FunctionDeclaration = FunctionDeclaration; + var FunctionExpression = (function () { + function FunctionExpression(id, params, body, generator) { + this.type = syntax_1.Syntax.FunctionExpression; + this.id = id; + this.params = params; + this.body = body; + this.generator = generator; + this.expression = false; + this.async = false; + } + return FunctionExpression; + }()); + exports.FunctionExpression = FunctionExpression; + var Identifier = (function () { + function Identifier(name) { + this.type = syntax_1.Syntax.Identifier; + this.name = name; + } + return Identifier; + }()); + exports.Identifier = Identifier; + var IfStatement = (function () { + function IfStatement(test, consequent, alternate) { + this.type = syntax_1.Syntax.IfStatement; + this.test = test; + this.consequent = consequent; + this.alternate = alternate; + } + return IfStatement; + }()); + exports.IfStatement = IfStatement; + var ImportDeclaration = (function () { + function ImportDeclaration(specifiers, source) { + this.type = syntax_1.Syntax.ImportDeclaration; + this.specifiers = specifiers; + this.source = source; + } + return ImportDeclaration; + }()); + exports.ImportDeclaration = ImportDeclaration; + var ImportDefaultSpecifier = (function () { + function ImportDefaultSpecifier(local) { + this.type = syntax_1.Syntax.ImportDefaultSpecifier; + this.local = local; + } + return ImportDefaultSpecifier; + }()); + exports.ImportDefaultSpecifier = ImportDefaultSpecifier; + var ImportNamespaceSpecifier = (function () { + function ImportNamespaceSpecifier(local) { + this.type = syntax_1.Syntax.ImportNamespaceSpecifier; + this.local = local; + } + return ImportNamespaceSpecifier; + }()); + exports.ImportNamespaceSpecifier = ImportNamespaceSpecifier; + var ImportSpecifier = (function () { + function ImportSpecifier(local, imported) { + this.type = syntax_1.Syntax.ImportSpecifier; + this.local = local; + this.imported = imported; + } + return ImportSpecifier; + }()); + exports.ImportSpecifier = ImportSpecifier; + var LabeledStatement = (function () { + function LabeledStatement(label, body) { + this.type = syntax_1.Syntax.LabeledStatement; + this.label = label; + this.body = body; + } + return LabeledStatement; + }()); + exports.LabeledStatement = LabeledStatement; + var Literal = (function () { + function Literal(value, raw) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + } + return Literal; + }()); + exports.Literal = Literal; + var MetaProperty = (function () { + function MetaProperty(meta, property) { + this.type = syntax_1.Syntax.MetaProperty; + this.meta = meta; + this.property = property; + } + return MetaProperty; + }()); + exports.MetaProperty = MetaProperty; + var MethodDefinition = (function () { + function MethodDefinition(key, computed, value, kind, isStatic) { + this.type = syntax_1.Syntax.MethodDefinition; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.static = isStatic; + } + return MethodDefinition; + }()); + exports.MethodDefinition = MethodDefinition; + var Module = (function () { + function Module(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'module'; + } + return Module; + }()); + exports.Module = Module; + var NewExpression = (function () { + function NewExpression(callee, args) { + this.type = syntax_1.Syntax.NewExpression; + this.callee = callee; + this.arguments = args; + } + return NewExpression; + }()); + exports.NewExpression = NewExpression; + var ObjectExpression = (function () { + function ObjectExpression(properties) { + this.type = syntax_1.Syntax.ObjectExpression; + this.properties = properties; + } + return ObjectExpression; + }()); + exports.ObjectExpression = ObjectExpression; + var ObjectPattern = (function () { + function ObjectPattern(properties) { + this.type = syntax_1.Syntax.ObjectPattern; + this.properties = properties; + } + return ObjectPattern; + }()); + exports.ObjectPattern = ObjectPattern; + var Property = (function () { + function Property(kind, key, computed, value, method, shorthand) { + this.type = syntax_1.Syntax.Property; + this.key = key; + this.computed = computed; + this.value = value; + this.kind = kind; + this.method = method; + this.shorthand = shorthand; + } + return Property; + }()); + exports.Property = Property; + var RegexLiteral = (function () { + function RegexLiteral(value, raw, pattern, flags) { + this.type = syntax_1.Syntax.Literal; + this.value = value; + this.raw = raw; + this.regex = { pattern: pattern, flags: flags }; + } + return RegexLiteral; + }()); + exports.RegexLiteral = RegexLiteral; + var RestElement = (function () { + function RestElement(argument) { + this.type = syntax_1.Syntax.RestElement; + this.argument = argument; + } + return RestElement; + }()); + exports.RestElement = RestElement; + var ReturnStatement = (function () { + function ReturnStatement(argument) { + this.type = syntax_1.Syntax.ReturnStatement; + this.argument = argument; + } + return ReturnStatement; + }()); + exports.ReturnStatement = ReturnStatement; + var Script = (function () { + function Script(body) { + this.type = syntax_1.Syntax.Program; + this.body = body; + this.sourceType = 'script'; + } + return Script; + }()); + exports.Script = Script; + var SequenceExpression = (function () { + function SequenceExpression(expressions) { + this.type = syntax_1.Syntax.SequenceExpression; + this.expressions = expressions; + } + return SequenceExpression; + }()); + exports.SequenceExpression = SequenceExpression; + var SpreadElement = (function () { + function SpreadElement(argument) { + this.type = syntax_1.Syntax.SpreadElement; + this.argument = argument; + } + return SpreadElement; + }()); + exports.SpreadElement = SpreadElement; + var StaticMemberExpression = (function () { + function StaticMemberExpression(object, property) { + this.type = syntax_1.Syntax.MemberExpression; + this.computed = false; + this.object = object; + this.property = property; + } + return StaticMemberExpression; + }()); + exports.StaticMemberExpression = StaticMemberExpression; + var Super = (function () { + function Super() { + this.type = syntax_1.Syntax.Super; + } + return Super; + }()); + exports.Super = Super; + var SwitchCase = (function () { + function SwitchCase(test, consequent) { + this.type = syntax_1.Syntax.SwitchCase; + this.test = test; + this.consequent = consequent; + } + return SwitchCase; + }()); + exports.SwitchCase = SwitchCase; + var SwitchStatement = (function () { + function SwitchStatement(discriminant, cases) { + this.type = syntax_1.Syntax.SwitchStatement; + this.discriminant = discriminant; + this.cases = cases; + } + return SwitchStatement; + }()); + exports.SwitchStatement = SwitchStatement; + var TaggedTemplateExpression = (function () { + function TaggedTemplateExpression(tag, quasi) { + this.type = syntax_1.Syntax.TaggedTemplateExpression; + this.tag = tag; + this.quasi = quasi; + } + return TaggedTemplateExpression; + }()); + exports.TaggedTemplateExpression = TaggedTemplateExpression; + var TemplateElement = (function () { + function TemplateElement(value, tail) { + this.type = syntax_1.Syntax.TemplateElement; + this.value = value; + this.tail = tail; + } + return TemplateElement; + }()); + exports.TemplateElement = TemplateElement; + var TemplateLiteral = (function () { + function TemplateLiteral(quasis, expressions) { + this.type = syntax_1.Syntax.TemplateLiteral; + this.quasis = quasis; + this.expressions = expressions; + } + return TemplateLiteral; + }()); + exports.TemplateLiteral = TemplateLiteral; + var ThisExpression = (function () { + function ThisExpression() { + this.type = syntax_1.Syntax.ThisExpression; + } + return ThisExpression; + }()); + exports.ThisExpression = ThisExpression; + var ThrowStatement = (function () { + function ThrowStatement(argument) { + this.type = syntax_1.Syntax.ThrowStatement; + this.argument = argument; + } + return ThrowStatement; + }()); + exports.ThrowStatement = ThrowStatement; + var TryStatement = (function () { + function TryStatement(block, handler, finalizer) { + this.type = syntax_1.Syntax.TryStatement; + this.block = block; + this.handler = handler; + this.finalizer = finalizer; + } + return TryStatement; + }()); + exports.TryStatement = TryStatement; + var UnaryExpression = (function () { + function UnaryExpression(operator, argument) { + this.type = syntax_1.Syntax.UnaryExpression; + this.operator = operator; + this.argument = argument; + this.prefix = true; + } + return UnaryExpression; + }()); + exports.UnaryExpression = UnaryExpression; + var UpdateExpression = (function () { + function UpdateExpression(operator, argument, prefix) { + this.type = syntax_1.Syntax.UpdateExpression; + this.operator = operator; + this.argument = argument; + this.prefix = prefix; + } + return UpdateExpression; + }()); + exports.UpdateExpression = UpdateExpression; + var VariableDeclaration = (function () { + function VariableDeclaration(declarations, kind) { + this.type = syntax_1.Syntax.VariableDeclaration; + this.declarations = declarations; + this.kind = kind; + } + return VariableDeclaration; + }()); + exports.VariableDeclaration = VariableDeclaration; + var VariableDeclarator = (function () { + function VariableDeclarator(id, init) { + this.type = syntax_1.Syntax.VariableDeclarator; + this.id = id; + this.init = init; + } + return VariableDeclarator; + }()); + exports.VariableDeclarator = VariableDeclarator; + var WhileStatement = (function () { + function WhileStatement(test, body) { + this.type = syntax_1.Syntax.WhileStatement; + this.test = test; + this.body = body; + } + return WhileStatement; + }()); + exports.WhileStatement = WhileStatement; + var WithStatement = (function () { + function WithStatement(object, body) { + this.type = syntax_1.Syntax.WithStatement; + this.object = object; + this.body = body; + } + return WithStatement; + }()); + exports.WithStatement = WithStatement; + var YieldExpression = (function () { + function YieldExpression(argument, delegate) { + this.type = syntax_1.Syntax.YieldExpression; + this.argument = argument; + this.delegate = delegate; + } + return YieldExpression; + }()); + exports.YieldExpression = YieldExpression; + + +/***/ }, +/* 8 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var error_handler_1 = __webpack_require__(10); + var messages_1 = __webpack_require__(11); + var Node = __webpack_require__(7); + var scanner_1 = __webpack_require__(12); + var syntax_1 = __webpack_require__(2); + var token_1 = __webpack_require__(13); + var ArrowParameterPlaceHolder = 'ArrowParameterPlaceHolder'; + var Parser = (function () { + function Parser(code, options, delegate) { + if (options === void 0) { options = {}; } + this.config = { + range: (typeof options.range === 'boolean') && options.range, + loc: (typeof options.loc === 'boolean') && options.loc, + source: null, + tokens: (typeof options.tokens === 'boolean') && options.tokens, + comment: (typeof options.comment === 'boolean') && options.comment, + tolerant: (typeof options.tolerant === 'boolean') && options.tolerant + }; + if (this.config.loc && options.source && options.source !== null) { + this.config.source = String(options.source); + } + this.delegate = delegate; + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = this.config.tolerant; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = this.config.comment; + this.operatorPrecedence = { + ')': 0, + ';': 0, + ',': 0, + '=': 0, + ']': 0, + '||': 1, + '&&': 2, + '|': 3, + '^': 4, + '&': 5, + '==': 6, + '!=': 6, + '===': 6, + '!==': 6, + '<': 7, + '>': 7, + '<=': 7, + '>=': 7, + '<<': 8, + '>>': 8, + '>>>': 8, + '+': 9, + '-': 9, + '*': 11, + '/': 11, + '%': 11 + }; + this.lookahead = { + type: 2 /* EOF */, + value: '', + lineNumber: this.scanner.lineNumber, + lineStart: 0, + start: 0, + end: 0 + }; + this.hasLineTerminator = false; + this.context = { + isModule: false, + await: false, + allowIn: true, + allowStrictDirective: true, + allowYield: true, + firstCoverInitializedNameError: null, + isAssignmentTarget: false, + isBindingElement: false, + inFunctionBody: false, + inIteration: false, + inSwitch: false, + labelSet: {}, + strict: false + }; + this.tokens = []; + this.startMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.lastMarker = { + index: 0, + line: this.scanner.lineNumber, + column: 0 + }; + this.nextToken(); + this.lastMarker = { + index: this.scanner.index, + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + } + Parser.prototype.throwError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + throw this.errorHandler.createError(index, line, column, msg); + }; + Parser.prototype.tolerateError = function (messageFormat) { + var values = []; + for (var _i = 1; _i < arguments.length; _i++) { + values[_i - 1] = arguments[_i]; + } + var args = Array.prototype.slice.call(arguments, 1); + var msg = messageFormat.replace(/%(\d)/g, function (whole, idx) { + assert_1.assert(idx < args.length, 'Message reference must be in range'); + return args[idx]; + }); + var index = this.lastMarker.index; + var line = this.scanner.lineNumber; + var column = this.lastMarker.column + 1; + this.errorHandler.tolerateError(index, line, column, msg); + }; + // Throw an exception because of the token. + Parser.prototype.unexpectedTokenError = function (token, message) { + var msg = message || messages_1.Messages.UnexpectedToken; + var value; + if (token) { + if (!message) { + msg = (token.type === 2 /* EOF */) ? messages_1.Messages.UnexpectedEOS : + (token.type === 3 /* Identifier */) ? messages_1.Messages.UnexpectedIdentifier : + (token.type === 6 /* NumericLiteral */) ? messages_1.Messages.UnexpectedNumber : + (token.type === 8 /* StringLiteral */) ? messages_1.Messages.UnexpectedString : + (token.type === 10 /* Template */) ? messages_1.Messages.UnexpectedTemplate : + messages_1.Messages.UnexpectedToken; + if (token.type === 4 /* Keyword */) { + if (this.scanner.isFutureReservedWord(token.value)) { + msg = messages_1.Messages.UnexpectedReserved; + } + else if (this.context.strict && this.scanner.isStrictModeReservedWord(token.value)) { + msg = messages_1.Messages.StrictReservedWord; + } + } + } + value = token.value; + } + else { + value = 'ILLEGAL'; + } + msg = msg.replace('%0', value); + if (token && typeof token.lineNumber === 'number') { + var index = token.start; + var line = token.lineNumber; + var lastMarkerLineStart = this.lastMarker.index - this.lastMarker.column; + var column = token.start - lastMarkerLineStart + 1; + return this.errorHandler.createError(index, line, column, msg); + } + else { + var index = this.lastMarker.index; + var line = this.lastMarker.line; + var column = this.lastMarker.column + 1; + return this.errorHandler.createError(index, line, column, msg); + } + }; + Parser.prototype.throwUnexpectedToken = function (token, message) { + throw this.unexpectedTokenError(token, message); + }; + Parser.prototype.tolerateUnexpectedToken = function (token, message) { + this.errorHandler.tolerate(this.unexpectedTokenError(token, message)); + }; + Parser.prototype.collectComments = function () { + if (!this.config.comment) { + this.scanner.scanComments(); + } + else { + var comments = this.scanner.scanComments(); + if (comments.length > 0 && this.delegate) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var node = void 0; + node = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: this.scanner.source.slice(e.slice[0], e.slice[1]) + }; + if (this.config.range) { + node.range = e.range; + } + if (this.config.loc) { + node.loc = e.loc; + } + var metadata = { + start: { + line: e.loc.start.line, + column: e.loc.start.column, + offset: e.range[0] + }, + end: { + line: e.loc.end.line, + column: e.loc.end.column, + offset: e.range[1] + } + }; + this.delegate(node, metadata); + } + } + } + }; + // From internal representation to an external structure + Parser.prototype.getTokenRaw = function (token) { + return this.scanner.source.slice(token.start, token.end); + }; + Parser.prototype.convertToken = function (token) { + var t = { + type: token_1.TokenName[token.type], + value: this.getTokenRaw(token) + }; + if (this.config.range) { + t.range = [token.start, token.end]; + } + if (this.config.loc) { + t.loc = { + start: { + line: this.startMarker.line, + column: this.startMarker.column + }, + end: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + } + }; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + t.regex = { pattern: pattern, flags: flags }; + } + return t; + }; + Parser.prototype.nextToken = function () { + var token = this.lookahead; + this.lastMarker.index = this.scanner.index; + this.lastMarker.line = this.scanner.lineNumber; + this.lastMarker.column = this.scanner.index - this.scanner.lineStart; + this.collectComments(); + if (this.scanner.index !== this.startMarker.index) { + this.startMarker.index = this.scanner.index; + this.startMarker.line = this.scanner.lineNumber; + this.startMarker.column = this.scanner.index - this.scanner.lineStart; + } + var next = this.scanner.lex(); + this.hasLineTerminator = (token.lineNumber !== next.lineNumber); + if (next && this.context.strict && next.type === 3 /* Identifier */) { + if (this.scanner.isStrictModeReservedWord(next.value)) { + next.type = 4 /* Keyword */; + } + } + this.lookahead = next; + if (this.config.tokens && next.type !== 2 /* EOF */) { + this.tokens.push(this.convertToken(next)); + } + return token; + }; + Parser.prototype.nextRegexToken = function () { + this.collectComments(); + var token = this.scanner.scanRegExp(); + if (this.config.tokens) { + // Pop the previous token, '/' or '/=' + // This is added from the lookahead token. + this.tokens.pop(); + this.tokens.push(this.convertToken(token)); + } + // Prime the next lookahead. + this.lookahead = token; + this.nextToken(); + return token; + }; + Parser.prototype.createNode = function () { + return { + index: this.startMarker.index, + line: this.startMarker.line, + column: this.startMarker.column + }; + }; + Parser.prototype.startNode = function (token) { + return { + index: token.start, + line: token.lineNumber, + column: token.start - token.lineStart + }; + }; + Parser.prototype.finalize = function (marker, node) { + if (this.config.range) { + node.range = [marker.index, this.lastMarker.index]; + } + if (this.config.loc) { + node.loc = { + start: { + line: marker.line, + column: marker.column, + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column + } + }; + if (this.config.source) { + node.loc.source = this.config.source; + } + } + if (this.delegate) { + var metadata = { + start: { + line: marker.line, + column: marker.column, + offset: marker.index + }, + end: { + line: this.lastMarker.line, + column: this.lastMarker.column, + offset: this.lastMarker.index + } + }; + this.delegate(node, metadata); + } + return node; + }; + // Expect the next token to match the specified punctuator. + // If not, an exception will be thrown. + Parser.prototype.expect = function (value) { + var token = this.nextToken(); + if (token.type !== 7 /* Punctuator */ || token.value !== value) { + this.throwUnexpectedToken(token); + } + }; + // Quietly expect a comma when in tolerant mode, otherwise delegates to expect(). + Parser.prototype.expectCommaSeparator = function () { + if (this.config.tolerant) { + var token = this.lookahead; + if (token.type === 7 /* Punctuator */ && token.value === ',') { + this.nextToken(); + } + else if (token.type === 7 /* Punctuator */ && token.value === ';') { + this.nextToken(); + this.tolerateUnexpectedToken(token); + } + else { + this.tolerateUnexpectedToken(token, messages_1.Messages.UnexpectedToken); + } + } + else { + this.expect(','); + } + }; + // Expect the next token to match the specified keyword. + // If not, an exception will be thrown. + Parser.prototype.expectKeyword = function (keyword) { + var token = this.nextToken(); + if (token.type !== 4 /* Keyword */ || token.value !== keyword) { + this.throwUnexpectedToken(token); + } + }; + // Return true if the next token matches the specified punctuator. + Parser.prototype.match = function (value) { + return this.lookahead.type === 7 /* Punctuator */ && this.lookahead.value === value; + }; + // Return true if the next token matches the specified keyword + Parser.prototype.matchKeyword = function (keyword) { + return this.lookahead.type === 4 /* Keyword */ && this.lookahead.value === keyword; + }; + // Return true if the next token matches the specified contextual keyword + // (where an identifier is sometimes a keyword depending on the context) + Parser.prototype.matchContextualKeyword = function (keyword) { + return this.lookahead.type === 3 /* Identifier */ && this.lookahead.value === keyword; + }; + // Return true if the next token is an assignment operator + Parser.prototype.matchAssign = function () { + if (this.lookahead.type !== 7 /* Punctuator */) { + return false; + } + var op = this.lookahead.value; + return op === '=' || + op === '*=' || + op === '**=' || + op === '/=' || + op === '%=' || + op === '+=' || + op === '-=' || + op === '<<=' || + op === '>>=' || + op === '>>>=' || + op === '&=' || + op === '^=' || + op === '|='; + }; + // Cover grammar support. + // + // When an assignment expression position starts with an left parenthesis, the determination of the type + // of the syntax is to be deferred arbitrarily long until the end of the parentheses pair (plus a lookahead) + // or the first comma. This situation also defers the determination of all the expressions nested in the pair. + // + // There are three productions that can be parsed in a parentheses pair that needs to be determined + // after the outermost pair is closed. They are: + // + // 1. AssignmentExpression + // 2. BindingElements + // 3. AssignmentTargets + // + // In order to avoid exponential backtracking, we use two flags to denote if the production can be + // binding element or assignment target. + // + // The three productions have the relationship: + // + // BindingElements ⊆ AssignmentTargets ⊆ AssignmentExpression + // + // with a single exception that CoverInitializedName when used directly in an Expression, generates + // an early error. Therefore, we need the third state, firstCoverInitializedNameError, to track the + // first usage of CoverInitializedName and report it when we reached the end of the parentheses pair. + // + // isolateCoverGrammar function runs the given parser function with a new cover grammar context, and it does not + // effect the current flags. This means the production the parser parses is only used as an expression. Therefore + // the CoverInitializedName check is conducted. + // + // inheritCoverGrammar function runs the given parse function with a new cover grammar context, and it propagates + // the flags outside of the parser. This means the production the parser parses is used as a part of a potential + // pattern. The CoverInitializedName check is deferred. + Parser.prototype.isolateCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + if (this.context.firstCoverInitializedNameError !== null) { + this.throwUnexpectedToken(this.context.firstCoverInitializedNameError); + } + this.context.isBindingElement = previousIsBindingElement; + this.context.isAssignmentTarget = previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError; + return result; + }; + Parser.prototype.inheritCoverGrammar = function (parseFunction) { + var previousIsBindingElement = this.context.isBindingElement; + var previousIsAssignmentTarget = this.context.isAssignmentTarget; + var previousFirstCoverInitializedNameError = this.context.firstCoverInitializedNameError; + this.context.isBindingElement = true; + this.context.isAssignmentTarget = true; + this.context.firstCoverInitializedNameError = null; + var result = parseFunction.call(this); + this.context.isBindingElement = this.context.isBindingElement && previousIsBindingElement; + this.context.isAssignmentTarget = this.context.isAssignmentTarget && previousIsAssignmentTarget; + this.context.firstCoverInitializedNameError = previousFirstCoverInitializedNameError || this.context.firstCoverInitializedNameError; + return result; + }; + Parser.prototype.consumeSemicolon = function () { + if (this.match(';')) { + this.nextToken(); + } + else if (!this.hasLineTerminator) { + if (this.lookahead.type !== 2 /* EOF */ && !this.match('}')) { + this.throwUnexpectedToken(this.lookahead); + } + this.lastMarker.index = this.startMarker.index; + this.lastMarker.line = this.startMarker.line; + this.lastMarker.column = this.startMarker.column; + } + }; + // https://tc39.github.io/ecma262/#sec-primary-expression + Parser.prototype.parsePrimaryExpression = function () { + var node = this.createNode(); + var expr; + var token, raw; + switch (this.lookahead.type) { + case 3 /* Identifier */: + if ((this.context.isModule || this.context.await) && this.lookahead.value === 'await') { + this.tolerateUnexpectedToken(this.lookahead); + } + expr = this.matchAsyncFunction() ? this.parseFunctionExpression() : this.finalize(node, new Node.Identifier(this.nextToken().value)); + break; + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + if (this.context.strict && this.lookahead.octal) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.StrictOctalLiteral); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 1 /* BooleanLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(token.value === 'true', raw)); + break; + case 5 /* NullLiteral */: + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + token = this.nextToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.Literal(null, raw)); + break; + case 10 /* Template */: + expr = this.parseTemplateLiteral(); + break; + case 7 /* Punctuator */: + switch (this.lookahead.value) { + case '(': + this.context.isBindingElement = false; + expr = this.inheritCoverGrammar(this.parseGroupExpression); + break; + case '[': + expr = this.inheritCoverGrammar(this.parseArrayInitializer); + break; + case '{': + expr = this.inheritCoverGrammar(this.parseObjectInitializer); + break; + case '/': + case '/=': + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.scanner.index = this.startMarker.index; + token = this.nextRegexToken(); + raw = this.getTokenRaw(token); + expr = this.finalize(node, new Node.RegexLiteral(token.regex, raw, token.pattern, token.flags)); + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + break; + case 4 /* Keyword */: + if (!this.context.strict && this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseIdentifierName(); + } + else if (!this.context.strict && this.matchKeyword('let')) { + expr = this.finalize(node, new Node.Identifier(this.nextToken().value)); + } + else { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + if (this.matchKeyword('function')) { + expr = this.parseFunctionExpression(); + } + else if (this.matchKeyword('this')) { + this.nextToken(); + expr = this.finalize(node, new Node.ThisExpression()); + } + else if (this.matchKeyword('class')) { + expr = this.parseClassExpression(); + } + else { + expr = this.throwUnexpectedToken(this.nextToken()); + } + } + break; + default: + expr = this.throwUnexpectedToken(this.nextToken()); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-array-initializer + Parser.prototype.parseSpreadElement = function () { + var node = this.createNode(); + this.expect('...'); + var arg = this.inheritCoverGrammar(this.parseAssignmentExpression); + return this.finalize(node, new Node.SpreadElement(arg)); + }; + Parser.prototype.parseArrayInitializer = function () { + var node = this.createNode(); + var elements = []; + this.expect('['); + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else if (this.match('...')) { + var element = this.parseSpreadElement(); + if (!this.match(']')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + this.expect(','); + } + elements.push(element); + } + else { + elements.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayExpression(elements)); + }; + // https://tc39.github.io/ecma262/#sec-object-initializer + Parser.prototype.parsePropertyMethod = function (params) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = params.simple; + var body = this.isolateCoverGrammar(this.parseFunctionSourceElements); + if (this.context.strict && params.firstRestricted) { + this.tolerateUnexpectedToken(params.firstRestricted, params.message); + } + if (this.context.strict && params.stricted) { + this.tolerateUnexpectedToken(params.stricted, params.message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + return body; + }; + Parser.prototype.parsePropertyMethodFunction = function () { + var isGenerator = false; + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + Parser.prototype.parsePropertyMethodAsyncFunction = function () { + var node = this.createNode(); + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = false; + this.context.await = true; + var params = this.parseFormalParameters(); + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + return this.finalize(node, new Node.AsyncFunctionExpression(null, params.params, method)); + }; + Parser.prototype.parseObjectPropertyKey = function () { + var node = this.createNode(); + var token = this.nextToken(); + var key; + switch (token.type) { + case 8 /* StringLiteral */: + case 6 /* NumericLiteral */: + if (this.context.strict && token.octal) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictOctalLiteral); + } + var raw = this.getTokenRaw(token); + key = this.finalize(node, new Node.Literal(token.value, raw)); + break; + case 3 /* Identifier */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 4 /* Keyword */: + key = this.finalize(node, new Node.Identifier(token.value)); + break; + case 7 /* Punctuator */: + if (token.value === '[') { + key = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.expect(']'); + } + else { + key = this.throwUnexpectedToken(token); + } + break; + default: + key = this.throwUnexpectedToken(token); + } + return key; + }; + Parser.prototype.isPropertyKey = function (key, value) { + return (key.type === syntax_1.Syntax.Identifier && key.name === value) || + (key.type === syntax_1.Syntax.Literal && key.value === value); + }; + Parser.prototype.parseObjectProperty = function (hasProto) { + var node = this.createNode(); + var token = this.lookahead; + var kind; + var key = null; + var value = null; + var computed = false; + var method = false; + var shorthand = false; + var isAsync = false; + if (token.type === 3 /* Identifier */) { + var id = token.value; + this.nextToken(); + computed = this.match('['); + isAsync = !this.hasLineTerminator && (id === 'async') && + !this.match(':') && !this.match('(') && !this.match('*'); + key = isAsync ? this.parseObjectPropertyKey() : this.finalize(node, new Node.Identifier(id)); + } + else if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.type === 3 /* Identifier */ && !isAsync && token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + else { + if (!key) { + this.throwUnexpectedToken(this.lookahead); + } + kind = 'init'; + if (this.match(':') && !isAsync) { + if (!computed && this.isPropertyKey(key, '__proto__')) { + if (hasProto.value) { + this.tolerateError(messages_1.Messages.DuplicateProtoProperty); + } + hasProto.value = true; + } + this.nextToken(); + value = this.inheritCoverGrammar(this.parseAssignmentExpression); + } + else if (this.match('(')) { + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + else if (token.type === 3 /* Identifier */) { + var id = this.finalize(node, new Node.Identifier(token.value)); + if (this.match('=')) { + this.context.firstCoverInitializedNameError = this.lookahead; + this.nextToken(); + shorthand = true; + var init = this.isolateCoverGrammar(this.parseAssignmentExpression); + value = this.finalize(node, new Node.AssignmentPattern(id, init)); + } + else { + shorthand = true; + value = id; + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.Property(kind, key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectInitializer = function () { + var node = this.createNode(); + this.expect('{'); + var properties = []; + var hasProto = { value: false }; + while (!this.match('}')) { + properties.push(this.parseObjectProperty(hasProto)); + if (!this.match('}')) { + this.expectCommaSeparator(); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectExpression(properties)); + }; + // https://tc39.github.io/ecma262/#sec-template-literals + Parser.prototype.parseTemplateHead = function () { + assert_1.assert(this.lookahead.head, 'Template literal must start with a template head'); + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateElement = function () { + if (this.lookahead.type !== 10 /* Template */) { + this.throwUnexpectedToken(); + } + var node = this.createNode(); + var token = this.nextToken(); + var raw = token.value; + var cooked = token.cooked; + return this.finalize(node, new Node.TemplateElement({ raw: raw, cooked: cooked }, token.tail)); + }; + Parser.prototype.parseTemplateLiteral = function () { + var node = this.createNode(); + var expressions = []; + var quasis = []; + var quasi = this.parseTemplateHead(); + quasis.push(quasi); + while (!quasi.tail) { + expressions.push(this.parseExpression()); + quasi = this.parseTemplateElement(); + quasis.push(quasi); + } + return this.finalize(node, new Node.TemplateLiteral(quasis, expressions)); + }; + // https://tc39.github.io/ecma262/#sec-grouping-operator + Parser.prototype.reinterpretExpressionAsPattern = function (expr) { + switch (expr.type) { + case syntax_1.Syntax.Identifier: + case syntax_1.Syntax.MemberExpression: + case syntax_1.Syntax.RestElement: + case syntax_1.Syntax.AssignmentPattern: + break; + case syntax_1.Syntax.SpreadElement: + expr.type = syntax_1.Syntax.RestElement; + this.reinterpretExpressionAsPattern(expr.argument); + break; + case syntax_1.Syntax.ArrayExpression: + expr.type = syntax_1.Syntax.ArrayPattern; + for (var i = 0; i < expr.elements.length; i++) { + if (expr.elements[i] !== null) { + this.reinterpretExpressionAsPattern(expr.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectExpression: + expr.type = syntax_1.Syntax.ObjectPattern; + for (var i = 0; i < expr.properties.length; i++) { + this.reinterpretExpressionAsPattern(expr.properties[i].value); + } + break; + case syntax_1.Syntax.AssignmentExpression: + expr.type = syntax_1.Syntax.AssignmentPattern; + delete expr.operator; + this.reinterpretExpressionAsPattern(expr.left); + break; + default: + // Allow other node type for tolerant parsing. + break; + } + }; + Parser.prototype.parseGroupExpression = function () { + var expr; + this.expect('('); + if (this.match(')')) { + this.nextToken(); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [], + async: false + }; + } + else { + var startToken = this.lookahead; + var params = []; + if (this.match('...')) { + expr = this.parseRestElement(params); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + else { + var arrow = false; + this.context.isBindingElement = true; + expr = this.inheritCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + this.context.isAssignmentTarget = false; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + if (this.match(')')) { + this.nextToken(); + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else if (this.match('...')) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + expressions.push(this.parseRestElement(params)); + this.expect(')'); + if (!this.match('=>')) { + this.expect('=>'); + } + this.context.isBindingElement = false; + for (var i = 0; i < expressions.length; i++) { + this.reinterpretExpressionAsPattern(expressions[i]); + } + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: expressions, + async: false + }; + } + else { + expressions.push(this.inheritCoverGrammar(this.parseAssignmentExpression)); + } + if (arrow) { + break; + } + } + if (!arrow) { + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + } + if (!arrow) { + this.expect(')'); + if (this.match('=>')) { + if (expr.type === syntax_1.Syntax.Identifier && expr.name === 'yield') { + arrow = true; + expr = { + type: ArrowParameterPlaceHolder, + params: [expr], + async: false + }; + } + if (!arrow) { + if (!this.context.isBindingElement) { + this.throwUnexpectedToken(this.lookahead); + } + if (expr.type === syntax_1.Syntax.SequenceExpression) { + for (var i = 0; i < expr.expressions.length; i++) { + this.reinterpretExpressionAsPattern(expr.expressions[i]); + } + } + else { + this.reinterpretExpressionAsPattern(expr); + } + var parameters = (expr.type === syntax_1.Syntax.SequenceExpression ? expr.expressions : [expr]); + expr = { + type: ArrowParameterPlaceHolder, + params: parameters, + async: false + }; + } + } + this.context.isBindingElement = false; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-left-hand-side-expressions + Parser.prototype.parseArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAssignmentExpression); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.isIdentifierName = function (token) { + return token.type === 3 /* Identifier */ || + token.type === 4 /* Keyword */ || + token.type === 1 /* BooleanLiteral */ || + token.type === 5 /* NullLiteral */; + }; + Parser.prototype.parseIdentifierName = function () { + var node = this.createNode(); + var token = this.nextToken(); + if (!this.isIdentifierName(token)) { + this.throwUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseNewExpression = function () { + var node = this.createNode(); + var id = this.parseIdentifierName(); + assert_1.assert(id.name === 'new', 'New expression must start with `new`'); + var expr; + if (this.match('.')) { + this.nextToken(); + if (this.lookahead.type === 3 /* Identifier */ && this.context.inFunctionBody && this.lookahead.value === 'target') { + var property = this.parseIdentifierName(); + expr = new Node.MetaProperty(id, property); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + var callee = this.isolateCoverGrammar(this.parseLeftHandSideExpression); + var args = this.match('(') ? this.parseArguments() : []; + expr = new Node.NewExpression(callee, args); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return this.finalize(node, expr); + }; + Parser.prototype.parseAsyncArgument = function () { + var arg = this.parseAssignmentExpression(); + this.context.firstCoverInitializedNameError = null; + return arg; + }; + Parser.prototype.parseAsyncArguments = function () { + this.expect('('); + var args = []; + if (!this.match(')')) { + while (true) { + var expr = this.match('...') ? this.parseSpreadElement() : + this.isolateCoverGrammar(this.parseAsyncArgument); + args.push(expr); + if (this.match(')')) { + break; + } + this.expectCommaSeparator(); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return args; + }; + Parser.prototype.parseLeftHandSideExpressionAllowCall = function () { + var startToken = this.lookahead; + var maybeAsync = this.matchContextualKeyword('async'); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var expr; + if (this.matchKeyword('super') && this.context.inFunctionBody) { + expr = this.createNode(); + this.nextToken(); + expr = this.finalize(expr, new Node.Super()); + if (!this.match('(') && !this.match('.') && !this.match('[')) { + this.throwUnexpectedToken(this.lookahead); + } + } + else { + expr = this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + } + while (true) { + if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(this.startNode(startToken), new Node.StaticMemberExpression(expr, property)); + } + else if (this.match('(')) { + var asyncArrow = maybeAsync && (startToken.lineNumber === this.lookahead.lineNumber); + this.context.isBindingElement = false; + this.context.isAssignmentTarget = false; + var args = asyncArrow ? this.parseAsyncArguments() : this.parseArguments(); + expr = this.finalize(this.startNode(startToken), new Node.CallExpression(expr, args)); + if (asyncArrow && this.match('=>')) { + for (var i = 0; i < args.length; ++i) { + this.reinterpretExpressionAsPattern(args[i]); + } + expr = { + type: ArrowParameterPlaceHolder, + params: args, + async: true + }; + } + } + else if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(this.startNode(startToken), new Node.ComputedMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(this.startNode(startToken), new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + this.context.allowIn = previousAllowIn; + return expr; + }; + Parser.prototype.parseSuper = function () { + var node = this.createNode(); + this.expectKeyword('super'); + if (!this.match('[') && !this.match('.')) { + this.throwUnexpectedToken(this.lookahead); + } + return this.finalize(node, new Node.Super()); + }; + Parser.prototype.parseLeftHandSideExpression = function () { + assert_1.assert(this.context.allowIn, 'callee of new expression always allow in keyword.'); + var node = this.startNode(this.lookahead); + var expr = (this.matchKeyword('super') && this.context.inFunctionBody) ? this.parseSuper() : + this.inheritCoverGrammar(this.matchKeyword('new') ? this.parseNewExpression : this.parsePrimaryExpression); + while (true) { + if (this.match('[')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('['); + var property = this.isolateCoverGrammar(this.parseExpression); + this.expect(']'); + expr = this.finalize(node, new Node.ComputedMemberExpression(expr, property)); + } + else if (this.match('.')) { + this.context.isBindingElement = false; + this.context.isAssignmentTarget = true; + this.expect('.'); + var property = this.parseIdentifierName(); + expr = this.finalize(node, new Node.StaticMemberExpression(expr, property)); + } + else if (this.lookahead.type === 10 /* Template */ && this.lookahead.head) { + var quasi = this.parseTemplateLiteral(); + expr = this.finalize(node, new Node.TaggedTemplateExpression(expr, quasi)); + } + else { + break; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-update-expressions + Parser.prototype.parseUpdateExpression = function () { + var expr; + var startToken = this.lookahead; + if (this.match('++') || this.match('--')) { + var node = this.startNode(startToken); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPrefix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + var prefix = true; + expr = this.finalize(node, new Node.UpdateExpression(token.value, expr, prefix)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + expr = this.inheritCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + if (!this.hasLineTerminator && this.lookahead.type === 7 /* Punctuator */) { + if (this.match('++') || this.match('--')) { + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier && this.scanner.isRestrictedWord(expr.name)) { + this.tolerateError(messages_1.Messages.StrictLHSPostfix); + } + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var operator = this.nextToken().value; + var prefix = false; + expr = this.finalize(this.startNode(startToken), new Node.UpdateExpression(operator, expr, prefix)); + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-unary-operators + Parser.prototype.parseAwaitExpression = function () { + var node = this.createNode(); + this.nextToken(); + var argument = this.parseUnaryExpression(); + return this.finalize(node, new Node.AwaitExpression(argument)); + }; + Parser.prototype.parseUnaryExpression = function () { + var expr; + if (this.match('+') || this.match('-') || this.match('~') || this.match('!') || + this.matchKeyword('delete') || this.matchKeyword('void') || this.matchKeyword('typeof')) { + var node = this.startNode(this.lookahead); + var token = this.nextToken(); + expr = this.inheritCoverGrammar(this.parseUnaryExpression); + expr = this.finalize(node, new Node.UnaryExpression(token.value, expr)); + if (this.context.strict && expr.operator === 'delete' && expr.argument.type === syntax_1.Syntax.Identifier) { + this.tolerateError(messages_1.Messages.StrictDelete); + } + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else if (this.context.await && this.matchContextualKeyword('await')) { + expr = this.parseAwaitExpression(); + } + else { + expr = this.parseUpdateExpression(); + } + return expr; + }; + Parser.prototype.parseExponentiationExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseUnaryExpression); + if (expr.type !== syntax_1.Syntax.UnaryExpression && this.match('**')) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + expr = this.finalize(this.startNode(startToken), new Node.BinaryExpression('**', left, right)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-exp-operator + // https://tc39.github.io/ecma262/#sec-multiplicative-operators + // https://tc39.github.io/ecma262/#sec-additive-operators + // https://tc39.github.io/ecma262/#sec-bitwise-shift-operators + // https://tc39.github.io/ecma262/#sec-relational-operators + // https://tc39.github.io/ecma262/#sec-equality-operators + // https://tc39.github.io/ecma262/#sec-binary-bitwise-operators + // https://tc39.github.io/ecma262/#sec-binary-logical-operators + Parser.prototype.binaryPrecedence = function (token) { + var op = token.value; + var precedence; + if (token.type === 7 /* Punctuator */) { + precedence = this.operatorPrecedence[op] || 0; + } + else if (token.type === 4 /* Keyword */) { + precedence = (op === 'instanceof' || (this.context.allowIn && op === 'in')) ? 7 : 0; + } + else { + precedence = 0; + } + return precedence; + }; + Parser.prototype.parseBinaryExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseExponentiationExpression); + var token = this.lookahead; + var prec = this.binaryPrecedence(token); + if (prec > 0) { + this.nextToken(); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var markers = [startToken, this.lookahead]; + var left = expr; + var right = this.isolateCoverGrammar(this.parseExponentiationExpression); + var stack = [left, token.value, right]; + var precedences = [prec]; + while (true) { + prec = this.binaryPrecedence(this.lookahead); + if (prec <= 0) { + break; + } + // Reduce: make a binary expression from the three topmost entries. + while ((stack.length > 2) && (prec <= precedences[precedences.length - 1])) { + right = stack.pop(); + var operator = stack.pop(); + precedences.pop(); + left = stack.pop(); + markers.pop(); + var node = this.startNode(markers[markers.length - 1]); + stack.push(this.finalize(node, new Node.BinaryExpression(operator, left, right))); + } + // Shift. + stack.push(this.nextToken().value); + precedences.push(prec); + markers.push(this.lookahead); + stack.push(this.isolateCoverGrammar(this.parseExponentiationExpression)); + } + // Final reduce to clean-up the stack. + var i = stack.length - 1; + expr = stack[i]; + markers.pop(); + while (i > 1) { + var node = this.startNode(markers.pop()); + var operator = stack[i - 1]; + expr = this.finalize(node, new Node.BinaryExpression(operator, stack[i - 2], expr)); + i -= 2; + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-conditional-operator + Parser.prototype.parseConditionalExpression = function () { + var startToken = this.lookahead; + var expr = this.inheritCoverGrammar(this.parseBinaryExpression); + if (this.match('?')) { + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + var consequent = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + this.expect(':'); + var alternate = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.ConditionalExpression(expr, consequent, alternate)); + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-assignment-operators + Parser.prototype.checkPatternParam = function (options, param) { + switch (param.type) { + case syntax_1.Syntax.Identifier: + this.validateParam(options, param, param.name); + break; + case syntax_1.Syntax.RestElement: + this.checkPatternParam(options, param.argument); + break; + case syntax_1.Syntax.AssignmentPattern: + this.checkPatternParam(options, param.left); + break; + case syntax_1.Syntax.ArrayPattern: + for (var i = 0; i < param.elements.length; i++) { + if (param.elements[i] !== null) { + this.checkPatternParam(options, param.elements[i]); + } + } + break; + case syntax_1.Syntax.ObjectPattern: + for (var i = 0; i < param.properties.length; i++) { + this.checkPatternParam(options, param.properties[i].value); + } + break; + default: + break; + } + options.simple = options.simple && (param instanceof Node.Identifier); + }; + Parser.prototype.reinterpretAsCoverFormalsList = function (expr) { + var params = [expr]; + var options; + var asyncArrow = false; + switch (expr.type) { + case syntax_1.Syntax.Identifier: + break; + case ArrowParameterPlaceHolder: + params = expr.params; + asyncArrow = expr.async; + break; + default: + return null; + } + options = { + simple: true, + paramSet: {} + }; + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.AssignmentPattern) { + if (param.right.type === syntax_1.Syntax.YieldExpression) { + if (param.right.argument) { + this.throwUnexpectedToken(this.lookahead); + } + param.right.type = syntax_1.Syntax.Identifier; + param.right.name = 'yield'; + delete param.right.argument; + delete param.right.delegate; + } + } + else if (asyncArrow && param.type === syntax_1.Syntax.Identifier && param.name === 'await') { + this.throwUnexpectedToken(this.lookahead); + } + this.checkPatternParam(options, param); + params[i] = param; + } + if (this.context.strict || !this.context.allowYield) { + for (var i = 0; i < params.length; ++i) { + var param = params[i]; + if (param.type === syntax_1.Syntax.YieldExpression) { + this.throwUnexpectedToken(this.lookahead); + } + } + } + if (options.message === messages_1.Messages.StrictParamDupe) { + var token = this.context.strict ? options.stricted : options.firstRestricted; + this.throwUnexpectedToken(token, options.message); + } + return { + simple: options.simple, + params: params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.parseAssignmentExpression = function () { + var expr; + if (!this.context.allowYield && this.matchKeyword('yield')) { + expr = this.parseYieldExpression(); + } + else { + var startToken = this.lookahead; + var token = startToken; + expr = this.parseConditionalExpression(); + if (token.type === 3 /* Identifier */ && (token.lineNumber === this.lookahead.lineNumber) && token.value === 'async') { + if (this.lookahead.type === 3 /* Identifier */ || this.matchKeyword('yield')) { + var arg = this.parsePrimaryExpression(); + this.reinterpretExpressionAsPattern(arg); + expr = { + type: ArrowParameterPlaceHolder, + params: [arg], + async: true + }; + } + } + if (expr.type === ArrowParameterPlaceHolder || this.match('=>')) { + // https://tc39.github.io/ecma262/#sec-arrow-function-definitions + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + var isAsync = expr.async; + var list = this.reinterpretAsCoverFormalsList(expr); + if (list) { + if (this.hasLineTerminator) { + this.tolerateUnexpectedToken(this.lookahead); + } + this.context.firstCoverInitializedNameError = null; + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = list.simple; + var previousAllowYield = this.context.allowYield; + var previousAwait = this.context.await; + this.context.allowYield = true; + this.context.await = isAsync; + var node = this.startNode(startToken); + this.expect('=>'); + var body = void 0; + if (this.match('{')) { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = true; + body = this.parseFunctionSourceElements(); + this.context.allowIn = previousAllowIn; + } + else { + body = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + var expression = body.type !== syntax_1.Syntax.BlockStatement; + if (this.context.strict && list.firstRestricted) { + this.throwUnexpectedToken(list.firstRestricted, list.message); + } + if (this.context.strict && list.stricted) { + this.tolerateUnexpectedToken(list.stricted, list.message); + } + expr = isAsync ? this.finalize(node, new Node.AsyncArrowFunctionExpression(list.params, body, expression)) : + this.finalize(node, new Node.ArrowFunctionExpression(list.params, body, expression)); + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.allowYield = previousAllowYield; + this.context.await = previousAwait; + } + } + else { + if (this.matchAssign()) { + if (!this.context.isAssignmentTarget) { + this.tolerateError(messages_1.Messages.InvalidLHSInAssignment); + } + if (this.context.strict && expr.type === syntax_1.Syntax.Identifier) { + var id = expr; + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictLHSAssignment); + } + if (this.scanner.isStrictModeReservedWord(id.name)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + } + if (!this.match('=')) { + this.context.isAssignmentTarget = false; + this.context.isBindingElement = false; + } + else { + this.reinterpretExpressionAsPattern(expr); + } + token = this.nextToken(); + var operator = token.value; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + expr = this.finalize(this.startNode(startToken), new Node.AssignmentExpression(operator, expr, right)); + this.context.firstCoverInitializedNameError = null; + } + } + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-comma-operator + Parser.prototype.parseExpression = function () { + var startToken = this.lookahead; + var expr = this.isolateCoverGrammar(this.parseAssignmentExpression); + if (this.match(',')) { + var expressions = []; + expressions.push(expr); + while (this.lookahead.type !== 2 /* EOF */) { + if (!this.match(',')) { + break; + } + this.nextToken(); + expressions.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + expr = this.finalize(this.startNode(startToken), new Node.SequenceExpression(expressions)); + } + return expr; + }; + // https://tc39.github.io/ecma262/#sec-block + Parser.prototype.parseStatementListItem = function () { + var statement; + this.context.isAssignmentTarget = true; + this.context.isBindingElement = true; + if (this.lookahead.type === 4 /* Keyword */) { + switch (this.lookahead.value) { + case 'export': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalExportDeclaration); + } + statement = this.parseExportDeclaration(); + break; + case 'import': + if (!this.context.isModule) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.IllegalImportDeclaration); + } + statement = this.parseImportDeclaration(); + break; + case 'const': + statement = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'class': + statement = this.parseClassDeclaration(); + break; + case 'let': + statement = this.isLexicalDeclaration() ? this.parseLexicalDeclaration({ inFor: false }) : this.parseStatement(); + break; + default: + statement = this.parseStatement(); + break; + } + } + else { + statement = this.parseStatement(); + } + return statement; + }; + Parser.prototype.parseBlock = function () { + var node = this.createNode(); + this.expect('{'); + var block = []; + while (true) { + if (this.match('}')) { + break; + } + block.push(this.parseStatementListItem()); + } + this.expect('}'); + return this.finalize(node, new Node.BlockStatement(block)); + }; + // https://tc39.github.io/ecma262/#sec-let-and-const-declarations + Parser.prototype.parseLexicalBinding = function (kind, options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, kind); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (kind === 'const') { + if (!this.matchKeyword('in') && !this.matchContextualKeyword('of')) { + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else { + this.throwError(messages_1.Messages.DeclarationMissingInitializer, 'const'); + } + } + } + else if ((!options.inFor && id.type !== syntax_1.Syntax.Identifier) || this.match('=')) { + this.expect('='); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseBindingList = function (kind, options) { + var list = [this.parseLexicalBinding(kind, options)]; + while (this.match(',')) { + this.nextToken(); + list.push(this.parseLexicalBinding(kind, options)); + } + return list; + }; + Parser.prototype.isLexicalDeclaration = function () { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + return (next.type === 3 /* Identifier */) || + (next.type === 7 /* Punctuator */ && next.value === '[') || + (next.type === 7 /* Punctuator */ && next.value === '{') || + (next.type === 4 /* Keyword */ && next.value === 'let') || + (next.type === 4 /* Keyword */ && next.value === 'yield'); + }; + Parser.prototype.parseLexicalDeclaration = function (options) { + var node = this.createNode(); + var kind = this.nextToken().value; + assert_1.assert(kind === 'let' || kind === 'const', 'Lexical declaration must be either let or const'); + var declarations = this.parseBindingList(kind, options); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, kind)); + }; + // https://tc39.github.io/ecma262/#sec-destructuring-binding-patterns + Parser.prototype.parseBindingRestElement = function (params, kind) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params, kind); + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseArrayPattern = function (params, kind) { + var node = this.createNode(); + this.expect('['); + var elements = []; + while (!this.match(']')) { + if (this.match(',')) { + this.nextToken(); + elements.push(null); + } + else { + if (this.match('...')) { + elements.push(this.parseBindingRestElement(params, kind)); + break; + } + else { + elements.push(this.parsePatternWithDefault(params, kind)); + } + if (!this.match(']')) { + this.expect(','); + } + } + } + this.expect(']'); + return this.finalize(node, new Node.ArrayPattern(elements)); + }; + Parser.prototype.parsePropertyPattern = function (params, kind) { + var node = this.createNode(); + var computed = false; + var shorthand = false; + var method = false; + var key; + var value; + if (this.lookahead.type === 3 /* Identifier */) { + var keyToken = this.lookahead; + key = this.parseVariableIdentifier(); + var init = this.finalize(node, new Node.Identifier(keyToken.value)); + if (this.match('=')) { + params.push(keyToken); + shorthand = true; + this.nextToken(); + var expr = this.parseAssignmentExpression(); + value = this.finalize(this.startNode(keyToken), new Node.AssignmentPattern(init, expr)); + } + else if (!this.match(':')) { + params.push(keyToken); + shorthand = true; + value = init; + } + else { + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.expect(':'); + value = this.parsePatternWithDefault(params, kind); + } + return this.finalize(node, new Node.Property('init', key, computed, value, method, shorthand)); + }; + Parser.prototype.parseObjectPattern = function (params, kind) { + var node = this.createNode(); + var properties = []; + this.expect('{'); + while (!this.match('}')) { + properties.push(this.parsePropertyPattern(params, kind)); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return this.finalize(node, new Node.ObjectPattern(properties)); + }; + Parser.prototype.parsePattern = function (params, kind) { + var pattern; + if (this.match('[')) { + pattern = this.parseArrayPattern(params, kind); + } + else if (this.match('{')) { + pattern = this.parseObjectPattern(params, kind); + } + else { + if (this.matchKeyword('let') && (kind === 'const' || kind === 'let')) { + this.tolerateUnexpectedToken(this.lookahead, messages_1.Messages.LetInLexicalBinding); + } + params.push(this.lookahead); + pattern = this.parseVariableIdentifier(kind); + } + return pattern; + }; + Parser.prototype.parsePatternWithDefault = function (params, kind) { + var startToken = this.lookahead; + var pattern = this.parsePattern(params, kind); + if (this.match('=')) { + this.nextToken(); + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var right = this.isolateCoverGrammar(this.parseAssignmentExpression); + this.context.allowYield = previousAllowYield; + pattern = this.finalize(this.startNode(startToken), new Node.AssignmentPattern(pattern, right)); + } + return pattern; + }; + // https://tc39.github.io/ecma262/#sec-variable-statement + Parser.prototype.parseVariableIdentifier = function (kind) { + var node = this.createNode(); + var token = this.nextToken(); + if (token.type === 4 /* Keyword */ && token.value === 'yield') { + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else if (!this.context.allowYield) { + this.throwUnexpectedToken(token); + } + } + else if (token.type !== 3 /* Identifier */) { + if (this.context.strict && token.type === 4 /* Keyword */ && this.scanner.isStrictModeReservedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictReservedWord); + } + else { + if (this.context.strict || token.value !== 'let' || kind !== 'var') { + this.throwUnexpectedToken(token); + } + } + } + else if ((this.context.isModule || this.context.await) && token.type === 3 /* Identifier */ && token.value === 'await') { + this.tolerateUnexpectedToken(token); + } + return this.finalize(node, new Node.Identifier(token.value)); + }; + Parser.prototype.parseVariableDeclaration = function (options) { + var node = this.createNode(); + var params = []; + var id = this.parsePattern(params, 'var'); + if (this.context.strict && id.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(id.name)) { + this.tolerateError(messages_1.Messages.StrictVarName); + } + } + var init = null; + if (this.match('=')) { + this.nextToken(); + init = this.isolateCoverGrammar(this.parseAssignmentExpression); + } + else if (id.type !== syntax_1.Syntax.Identifier && !options.inFor) { + this.expect('='); + } + return this.finalize(node, new Node.VariableDeclarator(id, init)); + }; + Parser.prototype.parseVariableDeclarationList = function (options) { + var opt = { inFor: options.inFor }; + var list = []; + list.push(this.parseVariableDeclaration(opt)); + while (this.match(',')) { + this.nextToken(); + list.push(this.parseVariableDeclaration(opt)); + } + return list; + }; + Parser.prototype.parseVariableStatement = function () { + var node = this.createNode(); + this.expectKeyword('var'); + var declarations = this.parseVariableDeclarationList({ inFor: false }); + this.consumeSemicolon(); + return this.finalize(node, new Node.VariableDeclaration(declarations, 'var')); + }; + // https://tc39.github.io/ecma262/#sec-empty-statement + Parser.prototype.parseEmptyStatement = function () { + var node = this.createNode(); + this.expect(';'); + return this.finalize(node, new Node.EmptyStatement()); + }; + // https://tc39.github.io/ecma262/#sec-expression-statement + Parser.prototype.parseExpressionStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ExpressionStatement(expr)); + }; + // https://tc39.github.io/ecma262/#sec-if-statement + Parser.prototype.parseIfClause = function () { + if (this.context.strict && this.matchKeyword('function')) { + this.tolerateError(messages_1.Messages.StrictFunction); + } + return this.parseStatement(); + }; + Parser.prototype.parseIfStatement = function () { + var node = this.createNode(); + var consequent; + var alternate = null; + this.expectKeyword('if'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + consequent = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + consequent = this.parseIfClause(); + if (this.matchKeyword('else')) { + this.nextToken(); + alternate = this.parseIfClause(); + } + } + return this.finalize(node, new Node.IfStatement(test, consequent, alternate)); + }; + // https://tc39.github.io/ecma262/#sec-do-while-statement + Parser.prototype.parseDoWhileStatement = function () { + var node = this.createNode(); + this.expectKeyword('do'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + var body = this.parseStatement(); + this.context.inIteration = previousInIteration; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + } + else { + this.expect(')'); + if (this.match(';')) { + this.nextToken(); + } + } + return this.finalize(node, new Node.DoWhileStatement(body, test)); + }; + // https://tc39.github.io/ecma262/#sec-while-statement + Parser.prototype.parseWhileStatement = function () { + var node = this.createNode(); + var body; + this.expectKeyword('while'); + this.expect('('); + var test = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.parseStatement(); + this.context.inIteration = previousInIteration; + } + return this.finalize(node, new Node.WhileStatement(test, body)); + }; + // https://tc39.github.io/ecma262/#sec-for-statement + // https://tc39.github.io/ecma262/#sec-for-in-and-for-of-statements + Parser.prototype.parseForStatement = function () { + var init = null; + var test = null; + var update = null; + var forIn = true; + var left, right; + var node = this.createNode(); + this.expectKeyword('for'); + this.expect('('); + if (this.match(';')) { + this.nextToken(); + } + else { + if (this.matchKeyword('var')) { + init = this.createNode(); + this.nextToken(); + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseVariableDeclarationList({ inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && this.matchKeyword('in')) { + var decl = declarations[0]; + if (decl.init && (decl.id.type === syntax_1.Syntax.ArrayPattern || decl.id.type === syntax_1.Syntax.ObjectPattern || this.context.strict)) { + this.tolerateError(messages_1.Messages.ForInOfLoopInitializer, 'for-in'); + } + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + init = this.finalize(init, new Node.VariableDeclaration(declarations, 'var')); + this.expect(';'); + } + } + else if (this.matchKeyword('const') || this.matchKeyword('let')) { + init = this.createNode(); + var kind = this.nextToken().value; + if (!this.context.strict && this.lookahead.value === 'in') { + init = this.finalize(init, new Node.Identifier(kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else { + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + var declarations = this.parseBindingList(kind, { inFor: true }); + this.context.allowIn = previousAllowIn; + if (declarations.length === 1 && declarations[0].init === null && this.matchKeyword('in')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseExpression(); + init = null; + } + else if (declarations.length === 1 && declarations[0].init === null && this.matchContextualKeyword('of')) { + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + this.nextToken(); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + this.consumeSemicolon(); + init = this.finalize(init, new Node.VariableDeclaration(declarations, kind)); + } + } + } + else { + var initStartToken = this.lookahead; + var previousAllowIn = this.context.allowIn; + this.context.allowIn = false; + init = this.inheritCoverGrammar(this.parseAssignmentExpression); + this.context.allowIn = previousAllowIn; + if (this.matchKeyword('in')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForIn); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseExpression(); + init = null; + } + else if (this.matchContextualKeyword('of')) { + if (!this.context.isAssignmentTarget || init.type === syntax_1.Syntax.AssignmentExpression) { + this.tolerateError(messages_1.Messages.InvalidLHSInForLoop); + } + this.nextToken(); + this.reinterpretExpressionAsPattern(init); + left = init; + right = this.parseAssignmentExpression(); + init = null; + forIn = false; + } + else { + if (this.match(',')) { + var initSeq = [init]; + while (this.match(',')) { + this.nextToken(); + initSeq.push(this.isolateCoverGrammar(this.parseAssignmentExpression)); + } + init = this.finalize(this.startNode(initStartToken), new Node.SequenceExpression(initSeq)); + } + this.expect(';'); + } + } + } + if (typeof left === 'undefined') { + if (!this.match(';')) { + test = this.parseExpression(); + } + this.expect(';'); + if (!this.match(')')) { + update = this.parseExpression(); + } + } + var body; + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + var previousInIteration = this.context.inIteration; + this.context.inIteration = true; + body = this.isolateCoverGrammar(this.parseStatement); + this.context.inIteration = previousInIteration; + } + return (typeof left === 'undefined') ? + this.finalize(node, new Node.ForStatement(init, test, update, body)) : + forIn ? this.finalize(node, new Node.ForInStatement(left, right, body)) : + this.finalize(node, new Node.ForOfStatement(left, right, body)); + }; + // https://tc39.github.io/ecma262/#sec-continue-statement + Parser.prototype.parseContinueStatement = function () { + var node = this.createNode(); + this.expectKeyword('continue'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + label = id; + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration) { + this.throwError(messages_1.Messages.IllegalContinue); + } + return this.finalize(node, new Node.ContinueStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-break-statement + Parser.prototype.parseBreakStatement = function () { + var node = this.createNode(); + this.expectKeyword('break'); + var label = null; + if (this.lookahead.type === 3 /* Identifier */ && !this.hasLineTerminator) { + var id = this.parseVariableIdentifier(); + var key = '$' + id.name; + if (!Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.UnknownLabel, id.name); + } + label = id; + } + this.consumeSemicolon(); + if (label === null && !this.context.inIteration && !this.context.inSwitch) { + this.throwError(messages_1.Messages.IllegalBreak); + } + return this.finalize(node, new Node.BreakStatement(label)); + }; + // https://tc39.github.io/ecma262/#sec-return-statement + Parser.prototype.parseReturnStatement = function () { + if (!this.context.inFunctionBody) { + this.tolerateError(messages_1.Messages.IllegalReturn); + } + var node = this.createNode(); + this.expectKeyword('return'); + var hasArgument = !this.match(';') && !this.match('}') && + !this.hasLineTerminator && this.lookahead.type !== 2 /* EOF */; + var argument = hasArgument ? this.parseExpression() : null; + this.consumeSemicolon(); + return this.finalize(node, new Node.ReturnStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-with-statement + Parser.prototype.parseWithStatement = function () { + if (this.context.strict) { + this.tolerateError(messages_1.Messages.StrictModeWith); + } + var node = this.createNode(); + var body; + this.expectKeyword('with'); + this.expect('('); + var object = this.parseExpression(); + if (!this.match(')') && this.config.tolerant) { + this.tolerateUnexpectedToken(this.nextToken()); + body = this.finalize(this.createNode(), new Node.EmptyStatement()); + } + else { + this.expect(')'); + body = this.parseStatement(); + } + return this.finalize(node, new Node.WithStatement(object, body)); + }; + // https://tc39.github.io/ecma262/#sec-switch-statement + Parser.prototype.parseSwitchCase = function () { + var node = this.createNode(); + var test; + if (this.matchKeyword('default')) { + this.nextToken(); + test = null; + } + else { + this.expectKeyword('case'); + test = this.parseExpression(); + } + this.expect(':'); + var consequent = []; + while (true) { + if (this.match('}') || this.matchKeyword('default') || this.matchKeyword('case')) { + break; + } + consequent.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.SwitchCase(test, consequent)); + }; + Parser.prototype.parseSwitchStatement = function () { + var node = this.createNode(); + this.expectKeyword('switch'); + this.expect('('); + var discriminant = this.parseExpression(); + this.expect(')'); + var previousInSwitch = this.context.inSwitch; + this.context.inSwitch = true; + var cases = []; + var defaultFound = false; + this.expect('{'); + while (true) { + if (this.match('}')) { + break; + } + var clause = this.parseSwitchCase(); + if (clause.test === null) { + if (defaultFound) { + this.throwError(messages_1.Messages.MultipleDefaultsInSwitch); + } + defaultFound = true; + } + cases.push(clause); + } + this.expect('}'); + this.context.inSwitch = previousInSwitch; + return this.finalize(node, new Node.SwitchStatement(discriminant, cases)); + }; + // https://tc39.github.io/ecma262/#sec-labelled-statements + Parser.prototype.parseLabelledStatement = function () { + var node = this.createNode(); + var expr = this.parseExpression(); + var statement; + if ((expr.type === syntax_1.Syntax.Identifier) && this.match(':')) { + this.nextToken(); + var id = expr; + var key = '$' + id.name; + if (Object.prototype.hasOwnProperty.call(this.context.labelSet, key)) { + this.throwError(messages_1.Messages.Redeclaration, 'Label', id.name); + } + this.context.labelSet[key] = true; + var body = void 0; + if (this.matchKeyword('class')) { + this.tolerateUnexpectedToken(this.lookahead); + body = this.parseClassDeclaration(); + } + else if (this.matchKeyword('function')) { + var token = this.lookahead; + var declaration = this.parseFunctionDeclaration(); + if (this.context.strict) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunction); + } + else if (declaration.generator) { + this.tolerateUnexpectedToken(token, messages_1.Messages.GeneratorInLegacyContext); + } + body = declaration; + } + else { + body = this.parseStatement(); + } + delete this.context.labelSet[key]; + statement = new Node.LabeledStatement(id, body); + } + else { + this.consumeSemicolon(); + statement = new Node.ExpressionStatement(expr); + } + return this.finalize(node, statement); + }; + // https://tc39.github.io/ecma262/#sec-throw-statement + Parser.prototype.parseThrowStatement = function () { + var node = this.createNode(); + this.expectKeyword('throw'); + if (this.hasLineTerminator) { + this.throwError(messages_1.Messages.NewlineAfterThrow); + } + var argument = this.parseExpression(); + this.consumeSemicolon(); + return this.finalize(node, new Node.ThrowStatement(argument)); + }; + // https://tc39.github.io/ecma262/#sec-try-statement + Parser.prototype.parseCatchClause = function () { + var node = this.createNode(); + this.expectKeyword('catch'); + this.expect('('); + if (this.match(')')) { + this.throwUnexpectedToken(this.lookahead); + } + var params = []; + var param = this.parsePattern(params); + var paramMap = {}; + for (var i = 0; i < params.length; i++) { + var key = '$' + params[i].value; + if (Object.prototype.hasOwnProperty.call(paramMap, key)) { + this.tolerateError(messages_1.Messages.DuplicateBinding, params[i].value); + } + paramMap[key] = true; + } + if (this.context.strict && param.type === syntax_1.Syntax.Identifier) { + if (this.scanner.isRestrictedWord(param.name)) { + this.tolerateError(messages_1.Messages.StrictCatchVariable); + } + } + this.expect(')'); + var body = this.parseBlock(); + return this.finalize(node, new Node.CatchClause(param, body)); + }; + Parser.prototype.parseFinallyClause = function () { + this.expectKeyword('finally'); + return this.parseBlock(); + }; + Parser.prototype.parseTryStatement = function () { + var node = this.createNode(); + this.expectKeyword('try'); + var block = this.parseBlock(); + var handler = this.matchKeyword('catch') ? this.parseCatchClause() : null; + var finalizer = this.matchKeyword('finally') ? this.parseFinallyClause() : null; + if (!handler && !finalizer) { + this.throwError(messages_1.Messages.NoCatchOrFinally); + } + return this.finalize(node, new Node.TryStatement(block, handler, finalizer)); + }; + // https://tc39.github.io/ecma262/#sec-debugger-statement + Parser.prototype.parseDebuggerStatement = function () { + var node = this.createNode(); + this.expectKeyword('debugger'); + this.consumeSemicolon(); + return this.finalize(node, new Node.DebuggerStatement()); + }; + // https://tc39.github.io/ecma262/#sec-ecmascript-language-statements-and-declarations + Parser.prototype.parseStatement = function () { + var statement; + switch (this.lookahead.type) { + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 8 /* StringLiteral */: + case 10 /* Template */: + case 9 /* RegularExpression */: + statement = this.parseExpressionStatement(); + break; + case 7 /* Punctuator */: + var value = this.lookahead.value; + if (value === '{') { + statement = this.parseBlock(); + } + else if (value === '(') { + statement = this.parseExpressionStatement(); + } + else if (value === ';') { + statement = this.parseEmptyStatement(); + } + else { + statement = this.parseExpressionStatement(); + } + break; + case 3 /* Identifier */: + statement = this.matchAsyncFunction() ? this.parseFunctionDeclaration() : this.parseLabelledStatement(); + break; + case 4 /* Keyword */: + switch (this.lookahead.value) { + case 'break': + statement = this.parseBreakStatement(); + break; + case 'continue': + statement = this.parseContinueStatement(); + break; + case 'debugger': + statement = this.parseDebuggerStatement(); + break; + case 'do': + statement = this.parseDoWhileStatement(); + break; + case 'for': + statement = this.parseForStatement(); + break; + case 'function': + statement = this.parseFunctionDeclaration(); + break; + case 'if': + statement = this.parseIfStatement(); + break; + case 'return': + statement = this.parseReturnStatement(); + break; + case 'switch': + statement = this.parseSwitchStatement(); + break; + case 'throw': + statement = this.parseThrowStatement(); + break; + case 'try': + statement = this.parseTryStatement(); + break; + case 'var': + statement = this.parseVariableStatement(); + break; + case 'while': + statement = this.parseWhileStatement(); + break; + case 'with': + statement = this.parseWithStatement(); + break; + default: + statement = this.parseExpressionStatement(); + break; + } + break; + default: + statement = this.throwUnexpectedToken(this.lookahead); + } + return statement; + }; + // https://tc39.github.io/ecma262/#sec-function-definitions + Parser.prototype.parseFunctionSourceElements = function () { + var node = this.createNode(); + this.expect('{'); + var body = this.parseDirectivePrologues(); + var previousLabelSet = this.context.labelSet; + var previousInIteration = this.context.inIteration; + var previousInSwitch = this.context.inSwitch; + var previousInFunctionBody = this.context.inFunctionBody; + this.context.labelSet = {}; + this.context.inIteration = false; + this.context.inSwitch = false; + this.context.inFunctionBody = true; + while (this.lookahead.type !== 2 /* EOF */) { + if (this.match('}')) { + break; + } + body.push(this.parseStatementListItem()); + } + this.expect('}'); + this.context.labelSet = previousLabelSet; + this.context.inIteration = previousInIteration; + this.context.inSwitch = previousInSwitch; + this.context.inFunctionBody = previousInFunctionBody; + return this.finalize(node, new Node.BlockStatement(body)); + }; + Parser.prototype.validateParam = function (options, param, name) { + var key = '$' + name; + if (this.context.strict) { + if (this.scanner.isRestrictedWord(name)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamName; + } + if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + else if (!options.firstRestricted) { + if (this.scanner.isRestrictedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictParamName; + } + else if (this.scanner.isStrictModeReservedWord(name)) { + options.firstRestricted = param; + options.message = messages_1.Messages.StrictReservedWord; + } + else if (Object.prototype.hasOwnProperty.call(options.paramSet, key)) { + options.stricted = param; + options.message = messages_1.Messages.StrictParamDupe; + } + } + /* istanbul ignore next */ + if (typeof Object.defineProperty === 'function') { + Object.defineProperty(options.paramSet, key, { value: true, enumerable: true, writable: true, configurable: true }); + } + else { + options.paramSet[key] = true; + } + }; + Parser.prototype.parseRestElement = function (params) { + var node = this.createNode(); + this.expect('...'); + var arg = this.parsePattern(params); + if (this.match('=')) { + this.throwError(messages_1.Messages.DefaultRestParameter); + } + if (!this.match(')')) { + this.throwError(messages_1.Messages.ParameterAfterRestParameter); + } + return this.finalize(node, new Node.RestElement(arg)); + }; + Parser.prototype.parseFormalParameter = function (options) { + var params = []; + var param = this.match('...') ? this.parseRestElement(params) : this.parsePatternWithDefault(params); + for (var i = 0; i < params.length; i++) { + this.validateParam(options, params[i], params[i].value); + } + options.simple = options.simple && (param instanceof Node.Identifier); + options.params.push(param); + }; + Parser.prototype.parseFormalParameters = function (firstRestricted) { + var options; + options = { + simple: true, + params: [], + firstRestricted: firstRestricted + }; + this.expect('('); + if (!this.match(')')) { + options.paramSet = {}; + while (this.lookahead.type !== 2 /* EOF */) { + this.parseFormalParameter(options); + if (this.match(')')) { + break; + } + this.expect(','); + if (this.match(')')) { + break; + } + } + } + this.expect(')'); + return { + simple: options.simple, + params: options.params, + stricted: options.stricted, + firstRestricted: options.firstRestricted, + message: options.message + }; + }; + Parser.prototype.matchAsyncFunction = function () { + var match = this.matchContextualKeyword('async'); + if (match) { + var state = this.scanner.saveState(); + this.scanner.scanComments(); + var next = this.scanner.lex(); + this.scanner.restoreState(state); + match = (state.lineNumber === next.lineNumber) && (next.type === 4 /* Keyword */) && (next.value === 'function'); + } + return match; + }; + Parser.prototype.parseFunctionDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted = null; + if (!identifierIsOptional || !this.match('(')) { + var token = this.lookahead; + id = this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionDeclaration(id, params, body)) : + this.finalize(node, new Node.FunctionDeclaration(id, params, body, isGenerator)); + }; + Parser.prototype.parseFunctionExpression = function () { + var node = this.createNode(); + var isAsync = this.matchContextualKeyword('async'); + if (isAsync) { + this.nextToken(); + } + this.expectKeyword('function'); + var isGenerator = isAsync ? false : this.match('*'); + if (isGenerator) { + this.nextToken(); + } + var message; + var id = null; + var firstRestricted; + var previousAllowAwait = this.context.await; + var previousAllowYield = this.context.allowYield; + this.context.await = isAsync; + this.context.allowYield = !isGenerator; + if (!this.match('(')) { + var token = this.lookahead; + id = (!this.context.strict && !isGenerator && this.matchKeyword('yield')) ? this.parseIdentifierName() : this.parseVariableIdentifier(); + if (this.context.strict) { + if (this.scanner.isRestrictedWord(token.value)) { + this.tolerateUnexpectedToken(token, messages_1.Messages.StrictFunctionName); + } + } + else { + if (this.scanner.isRestrictedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictFunctionName; + } + else if (this.scanner.isStrictModeReservedWord(token.value)) { + firstRestricted = token; + message = messages_1.Messages.StrictReservedWord; + } + } + } + var formalParameters = this.parseFormalParameters(firstRestricted); + var params = formalParameters.params; + var stricted = formalParameters.stricted; + firstRestricted = formalParameters.firstRestricted; + if (formalParameters.message) { + message = formalParameters.message; + } + var previousStrict = this.context.strict; + var previousAllowStrictDirective = this.context.allowStrictDirective; + this.context.allowStrictDirective = formalParameters.simple; + var body = this.parseFunctionSourceElements(); + if (this.context.strict && firstRestricted) { + this.throwUnexpectedToken(firstRestricted, message); + } + if (this.context.strict && stricted) { + this.tolerateUnexpectedToken(stricted, message); + } + this.context.strict = previousStrict; + this.context.allowStrictDirective = previousAllowStrictDirective; + this.context.await = previousAllowAwait; + this.context.allowYield = previousAllowYield; + return isAsync ? this.finalize(node, new Node.AsyncFunctionExpression(id, params, body)) : + this.finalize(node, new Node.FunctionExpression(id, params, body, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-directive-prologues-and-the-use-strict-directive + Parser.prototype.parseDirective = function () { + var token = this.lookahead; + var node = this.createNode(); + var expr = this.parseExpression(); + var directive = (expr.type === syntax_1.Syntax.Literal) ? this.getTokenRaw(token).slice(1, -1) : null; + this.consumeSemicolon(); + return this.finalize(node, directive ? new Node.Directive(expr, directive) : new Node.ExpressionStatement(expr)); + }; + Parser.prototype.parseDirectivePrologues = function () { + var firstRestricted = null; + var body = []; + while (true) { + var token = this.lookahead; + if (token.type !== 8 /* StringLiteral */) { + break; + } + var statement = this.parseDirective(); + body.push(statement); + var directive = statement.directive; + if (typeof directive !== 'string') { + break; + } + if (directive === 'use strict') { + this.context.strict = true; + if (firstRestricted) { + this.tolerateUnexpectedToken(firstRestricted, messages_1.Messages.StrictOctalLiteral); + } + if (!this.context.allowStrictDirective) { + this.tolerateUnexpectedToken(token, messages_1.Messages.IllegalLanguageModeDirective); + } + } + else { + if (!firstRestricted && token.octal) { + firstRestricted = token; + } + } + } + return body; + }; + // https://tc39.github.io/ecma262/#sec-method-definitions + Parser.prototype.qualifiedPropertyName = function (token) { + switch (token.type) { + case 3 /* Identifier */: + case 8 /* StringLiteral */: + case 1 /* BooleanLiteral */: + case 5 /* NullLiteral */: + case 6 /* NumericLiteral */: + case 4 /* Keyword */: + return true; + case 7 /* Punctuator */: + return token.value === '['; + default: + break; + } + return false; + }; + Parser.prototype.parseGetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length > 0) { + this.tolerateError(messages_1.Messages.BadGetterArity); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseSetterMethod = function () { + var node = this.createNode(); + var isGenerator = false; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + var formalParameters = this.parseFormalParameters(); + if (formalParameters.params.length !== 1) { + this.tolerateError(messages_1.Messages.BadSetterArity); + } + else if (formalParameters.params[0] instanceof Node.RestElement) { + this.tolerateError(messages_1.Messages.BadSetterRestParameter); + } + var method = this.parsePropertyMethod(formalParameters); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, formalParameters.params, method, isGenerator)); + }; + Parser.prototype.parseGeneratorMethod = function () { + var node = this.createNode(); + var isGenerator = true; + var previousAllowYield = this.context.allowYield; + this.context.allowYield = true; + var params = this.parseFormalParameters(); + this.context.allowYield = false; + var method = this.parsePropertyMethod(params); + this.context.allowYield = previousAllowYield; + return this.finalize(node, new Node.FunctionExpression(null, params.params, method, isGenerator)); + }; + // https://tc39.github.io/ecma262/#sec-generator-function-definitions + Parser.prototype.isStartOfExpression = function () { + var start = true; + var value = this.lookahead.value; + switch (this.lookahead.type) { + case 7 /* Punctuator */: + start = (value === '[') || (value === '(') || (value === '{') || + (value === '+') || (value === '-') || + (value === '!') || (value === '~') || + (value === '++') || (value === '--') || + (value === '/') || (value === '/='); // regular expression literal + break; + case 4 /* Keyword */: + start = (value === 'class') || (value === 'delete') || + (value === 'function') || (value === 'let') || (value === 'new') || + (value === 'super') || (value === 'this') || (value === 'typeof') || + (value === 'void') || (value === 'yield'); + break; + default: + break; + } + return start; + }; + Parser.prototype.parseYieldExpression = function () { + var node = this.createNode(); + this.expectKeyword('yield'); + var argument = null; + var delegate = false; + if (!this.hasLineTerminator) { + var previousAllowYield = this.context.allowYield; + this.context.allowYield = false; + delegate = this.match('*'); + if (delegate) { + this.nextToken(); + argument = this.parseAssignmentExpression(); + } + else if (this.isStartOfExpression()) { + argument = this.parseAssignmentExpression(); + } + this.context.allowYield = previousAllowYield; + } + return this.finalize(node, new Node.YieldExpression(argument, delegate)); + }; + // https://tc39.github.io/ecma262/#sec-class-definitions + Parser.prototype.parseClassElement = function (hasConstructor) { + var token = this.lookahead; + var node = this.createNode(); + var kind = ''; + var key = null; + var value = null; + var computed = false; + var method = false; + var isStatic = false; + var isAsync = false; + if (this.match('*')) { + this.nextToken(); + } + else { + computed = this.match('['); + key = this.parseObjectPropertyKey(); + var id = key; + if (id.name === 'static' && (this.qualifiedPropertyName(this.lookahead) || this.match('*'))) { + token = this.lookahead; + isStatic = true; + computed = this.match('['); + if (this.match('*')) { + this.nextToken(); + } + else { + key = this.parseObjectPropertyKey(); + } + } + if ((token.type === 3 /* Identifier */) && !this.hasLineTerminator && (token.value === 'async')) { + var punctuator = this.lookahead.value; + if (punctuator !== ':' && punctuator !== '(' && punctuator !== '*') { + isAsync = true; + token = this.lookahead; + key = this.parseObjectPropertyKey(); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' || token.value === 'set') { + this.tolerateUnexpectedToken(token); + } + else if (token.value === 'constructor') { + this.tolerateUnexpectedToken(token, messages_1.Messages.ConstructorIsAsync); + } + } + } + } + } + var lookaheadPropertyKey = this.qualifiedPropertyName(this.lookahead); + if (token.type === 3 /* Identifier */) { + if (token.value === 'get' && lookaheadPropertyKey) { + kind = 'get'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + this.context.allowYield = false; + value = this.parseGetterMethod(); + } + else if (token.value === 'set' && lookaheadPropertyKey) { + kind = 'set'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseSetterMethod(); + } + } + else if (token.type === 7 /* Punctuator */ && token.value === '*' && lookaheadPropertyKey) { + kind = 'init'; + computed = this.match('['); + key = this.parseObjectPropertyKey(); + value = this.parseGeneratorMethod(); + method = true; + } + if (!kind && key && this.match('(')) { + kind = 'init'; + value = isAsync ? this.parsePropertyMethodAsyncFunction() : this.parsePropertyMethodFunction(); + method = true; + } + if (!kind) { + this.throwUnexpectedToken(this.lookahead); + } + if (kind === 'init') { + kind = 'method'; + } + if (!computed) { + if (isStatic && this.isPropertyKey(key, 'prototype')) { + this.throwUnexpectedToken(token, messages_1.Messages.StaticPrototype); + } + if (!isStatic && this.isPropertyKey(key, 'constructor')) { + if (kind !== 'method' || !method || (value && value.generator)) { + this.throwUnexpectedToken(token, messages_1.Messages.ConstructorSpecialMethod); + } + if (hasConstructor.value) { + this.throwUnexpectedToken(token, messages_1.Messages.DuplicateConstructor); + } + else { + hasConstructor.value = true; + } + kind = 'constructor'; + } + } + return this.finalize(node, new Node.MethodDefinition(key, computed, value, kind, isStatic)); + }; + Parser.prototype.parseClassElementList = function () { + var body = []; + var hasConstructor = { value: false }; + this.expect('{'); + while (!this.match('}')) { + if (this.match(';')) { + this.nextToken(); + } + else { + body.push(this.parseClassElement(hasConstructor)); + } + } + this.expect('}'); + return body; + }; + Parser.prototype.parseClassBody = function () { + var node = this.createNode(); + var elementList = this.parseClassElementList(); + return this.finalize(node, new Node.ClassBody(elementList)); + }; + Parser.prototype.parseClassDeclaration = function (identifierIsOptional) { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (identifierIsOptional && (this.lookahead.type !== 3 /* Identifier */)) ? null : this.parseVariableIdentifier(); + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassDeclaration(id, superClass, classBody)); + }; + Parser.prototype.parseClassExpression = function () { + var node = this.createNode(); + var previousStrict = this.context.strict; + this.context.strict = true; + this.expectKeyword('class'); + var id = (this.lookahead.type === 3 /* Identifier */) ? this.parseVariableIdentifier() : null; + var superClass = null; + if (this.matchKeyword('extends')) { + this.nextToken(); + superClass = this.isolateCoverGrammar(this.parseLeftHandSideExpressionAllowCall); + } + var classBody = this.parseClassBody(); + this.context.strict = previousStrict; + return this.finalize(node, new Node.ClassExpression(id, superClass, classBody)); + }; + // https://tc39.github.io/ecma262/#sec-scripts + // https://tc39.github.io/ecma262/#sec-modules + Parser.prototype.parseModule = function () { + this.context.strict = true; + this.context.isModule = true; + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Module(body)); + }; + Parser.prototype.parseScript = function () { + var node = this.createNode(); + var body = this.parseDirectivePrologues(); + while (this.lookahead.type !== 2 /* EOF */) { + body.push(this.parseStatementListItem()); + } + return this.finalize(node, new Node.Script(body)); + }; + // https://tc39.github.io/ecma262/#sec-imports + Parser.prototype.parseModuleSpecifier = function () { + var node = this.createNode(); + if (this.lookahead.type !== 8 /* StringLiteral */) { + this.throwError(messages_1.Messages.InvalidModuleSpecifier); + } + var token = this.nextToken(); + var raw = this.getTokenRaw(token); + return this.finalize(node, new Node.Literal(token.value, raw)); + }; + // import {<foo as bar>} ...; + Parser.prototype.parseImportSpecifier = function () { + var node = this.createNode(); + var imported; + var local; + if (this.lookahead.type === 3 /* Identifier */) { + imported = this.parseVariableIdentifier(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + } + else { + imported = this.parseIdentifierName(); + local = imported; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + local = this.parseVariableIdentifier(); + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + } + return this.finalize(node, new Node.ImportSpecifier(local, imported)); + }; + // {foo, bar as bas} + Parser.prototype.parseNamedImports = function () { + this.expect('{'); + var specifiers = []; + while (!this.match('}')) { + specifiers.push(this.parseImportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + return specifiers; + }; + // import <foo> ...; + Parser.prototype.parseImportDefaultSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportDefaultSpecifier(local)); + }; + // import <* as foo> ...; + Parser.prototype.parseImportNamespaceSpecifier = function () { + var node = this.createNode(); + this.expect('*'); + if (!this.matchContextualKeyword('as')) { + this.throwError(messages_1.Messages.NoAsAfterImportNamespace); + } + this.nextToken(); + var local = this.parseIdentifierName(); + return this.finalize(node, new Node.ImportNamespaceSpecifier(local)); + }; + Parser.prototype.parseImportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalImportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('import'); + var src; + var specifiers = []; + if (this.lookahead.type === 8 /* StringLiteral */) { + // import 'foo'; + src = this.parseModuleSpecifier(); + } + else { + if (this.match('{')) { + // import {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else if (this.match('*')) { + // import * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.isIdentifierName(this.lookahead) && !this.matchKeyword('default')) { + // import foo + specifiers.push(this.parseImportDefaultSpecifier()); + if (this.match(',')) { + this.nextToken(); + if (this.match('*')) { + // import foo, * as foo + specifiers.push(this.parseImportNamespaceSpecifier()); + } + else if (this.match('{')) { + // import foo, {bar} + specifiers = specifiers.concat(this.parseNamedImports()); + } + else { + this.throwUnexpectedToken(this.lookahead); + } + } + } + else { + this.throwUnexpectedToken(this.nextToken()); + } + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + src = this.parseModuleSpecifier(); + } + this.consumeSemicolon(); + return this.finalize(node, new Node.ImportDeclaration(specifiers, src)); + }; + // https://tc39.github.io/ecma262/#sec-exports + Parser.prototype.parseExportSpecifier = function () { + var node = this.createNode(); + var local = this.parseIdentifierName(); + var exported = local; + if (this.matchContextualKeyword('as')) { + this.nextToken(); + exported = this.parseIdentifierName(); + } + return this.finalize(node, new Node.ExportSpecifier(local, exported)); + }; + Parser.prototype.parseExportDeclaration = function () { + if (this.context.inFunctionBody) { + this.throwError(messages_1.Messages.IllegalExportDeclaration); + } + var node = this.createNode(); + this.expectKeyword('export'); + var exportDeclaration; + if (this.matchKeyword('default')) { + // export default ... + this.nextToken(); + if (this.matchKeyword('function')) { + // export default function foo () {} + // export default function () {} + var declaration = this.parseFunctionDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchKeyword('class')) { + // export default class foo {} + var declaration = this.parseClassDeclaration(true); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else if (this.matchContextualKeyword('async')) { + // export default async function f () {} + // export default async function () {} + // export default async x => x + var declaration = this.matchAsyncFunction() ? this.parseFunctionDeclaration(true) : this.parseAssignmentExpression(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + else { + if (this.matchContextualKeyword('from')) { + this.throwError(messages_1.Messages.UnexpectedToken, this.lookahead.value); + } + // export default {}; + // export default []; + // export default (1 + 2); + var declaration = this.match('{') ? this.parseObjectInitializer() : + this.match('[') ? this.parseArrayInitializer() : this.parseAssignmentExpression(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportDefaultDeclaration(declaration)); + } + } + else if (this.match('*')) { + // export * from 'foo'; + this.nextToken(); + if (!this.matchContextualKeyword('from')) { + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + this.nextToken(); + var src = this.parseModuleSpecifier(); + this.consumeSemicolon(); + exportDeclaration = this.finalize(node, new Node.ExportAllDeclaration(src)); + } + else if (this.lookahead.type === 4 /* Keyword */) { + // export var f = 1; + var declaration = void 0; + switch (this.lookahead.value) { + case 'let': + case 'const': + declaration = this.parseLexicalDeclaration({ inFor: false }); + break; + case 'var': + case 'class': + case 'function': + declaration = this.parseStatementListItem(); + break; + default: + this.throwUnexpectedToken(this.lookahead); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else if (this.matchAsyncFunction()) { + var declaration = this.parseFunctionDeclaration(); + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(declaration, [], null)); + } + else { + var specifiers = []; + var source = null; + var isExportFromIdentifier = false; + this.expect('{'); + while (!this.match('}')) { + isExportFromIdentifier = isExportFromIdentifier || this.matchKeyword('default'); + specifiers.push(this.parseExportSpecifier()); + if (!this.match('}')) { + this.expect(','); + } + } + this.expect('}'); + if (this.matchContextualKeyword('from')) { + // export {default} from 'foo'; + // export {foo} from 'foo'; + this.nextToken(); + source = this.parseModuleSpecifier(); + this.consumeSemicolon(); + } + else if (isExportFromIdentifier) { + // export {default}; // missing fromClause + var message = this.lookahead.value ? messages_1.Messages.UnexpectedToken : messages_1.Messages.MissingFromClause; + this.throwError(message, this.lookahead.value); + } + else { + // export {foo}; + this.consumeSemicolon(); + } + exportDeclaration = this.finalize(node, new Node.ExportNamedDeclaration(null, specifiers, source)); + } + return exportDeclaration; + }; + return Parser; + }()); + exports.Parser = Parser; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + "use strict"; + // Ensure the condition is true, otherwise throw an error. + // This is only to have a better contract semantic, i.e. another safety net + // to catch a logic error. The condition shall be fulfilled in normal case. + // Do NOT use this to enforce a certain condition on any user input. + Object.defineProperty(exports, "__esModule", { value: true }); + function assert(condition, message) { + /* istanbul ignore if */ + if (!condition) { + throw new Error('ASSERT: ' + message); + } + } + exports.assert = assert; + + +/***/ }, +/* 10 */ +/***/ function(module, exports) { + + "use strict"; + /* tslint:disable:max-classes-per-file */ + Object.defineProperty(exports, "__esModule", { value: true }); + var ErrorHandler = (function () { + function ErrorHandler() { + this.errors = []; + this.tolerant = false; + } + ErrorHandler.prototype.recordError = function (error) { + this.errors.push(error); + }; + ErrorHandler.prototype.tolerate = function (error) { + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + ErrorHandler.prototype.constructError = function (msg, column) { + var error = new Error(msg); + try { + throw error; + } + catch (base) { + /* istanbul ignore else */ + if (Object.create && Object.defineProperty) { + error = Object.create(base); + Object.defineProperty(error, 'column', { value: column }); + } + } + /* istanbul ignore next */ + return error; + }; + ErrorHandler.prototype.createError = function (index, line, col, description) { + var msg = 'Line ' + line + ': ' + description; + var error = this.constructError(msg, col); + error.index = index; + error.lineNumber = line; + error.description = description; + return error; + }; + ErrorHandler.prototype.throwError = function (index, line, col, description) { + throw this.createError(index, line, col, description); + }; + ErrorHandler.prototype.tolerateError = function (index, line, col, description) { + var error = this.createError(index, line, col, description); + if (this.tolerant) { + this.recordError(error); + } + else { + throw error; + } + }; + return ErrorHandler; + }()); + exports.ErrorHandler = ErrorHandler; + + +/***/ }, +/* 11 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + // Error messages should be identical to V8. + exports.Messages = { + BadGetterArity: 'Getter must not have any formal parameters', + BadSetterArity: 'Setter must have exactly one formal parameter', + BadSetterRestParameter: 'Setter function argument must not be a rest parameter', + ConstructorIsAsync: 'Class constructor may not be an async method', + ConstructorSpecialMethod: 'Class constructor may not be an accessor', + DeclarationMissingInitializer: 'Missing initializer in %0 declaration', + DefaultRestParameter: 'Unexpected token =', + DuplicateBinding: 'Duplicate binding %0', + DuplicateConstructor: 'A class may only have one constructor', + DuplicateProtoProperty: 'Duplicate __proto__ fields are not allowed in object literals', + ForInOfLoopInitializer: '%0 loop variable declaration may not have an initializer', + GeneratorInLegacyContext: 'Generator declarations are not allowed in legacy contexts', + IllegalBreak: 'Illegal break statement', + IllegalContinue: 'Illegal continue statement', + IllegalExportDeclaration: 'Unexpected token', + IllegalImportDeclaration: 'Unexpected token', + IllegalLanguageModeDirective: 'Illegal \'use strict\' directive in function with non-simple parameter list', + IllegalReturn: 'Illegal return statement', + InvalidEscapedReservedWord: 'Keyword must not contain escaped characters', + InvalidHexEscapeSequence: 'Invalid hexadecimal escape sequence', + InvalidLHSInAssignment: 'Invalid left-hand side in assignment', + InvalidLHSInForIn: 'Invalid left-hand side in for-in', + InvalidLHSInForLoop: 'Invalid left-hand side in for-loop', + InvalidModuleSpecifier: 'Unexpected token', + InvalidRegExp: 'Invalid regular expression', + LetInLexicalBinding: 'let is disallowed as a lexically bound name', + MissingFromClause: 'Unexpected token', + MultipleDefaultsInSwitch: 'More than one default clause in switch statement', + NewlineAfterThrow: 'Illegal newline after throw', + NoAsAfterImportNamespace: 'Unexpected token', + NoCatchOrFinally: 'Missing catch or finally after try', + ParameterAfterRestParameter: 'Rest parameter must be last formal parameter', + Redeclaration: '%0 \'%1\' has already been declared', + StaticPrototype: 'Classes may not have static property named prototype', + StrictCatchVariable: 'Catch variable may not be eval or arguments in strict mode', + StrictDelete: 'Delete of an unqualified identifier in strict mode.', + StrictFunction: 'In strict mode code, functions can only be declared at top level or inside a block', + StrictFunctionName: 'Function name may not be eval or arguments in strict mode', + StrictLHSAssignment: 'Assignment to eval or arguments is not allowed in strict mode', + StrictLHSPostfix: 'Postfix increment/decrement may not have eval or arguments operand in strict mode', + StrictLHSPrefix: 'Prefix increment/decrement may not have eval or arguments operand in strict mode', + StrictModeWith: 'Strict mode code may not include a with statement', + StrictOctalLiteral: 'Octal literals are not allowed in strict mode.', + StrictParamDupe: 'Strict mode function may not have duplicate parameter names', + StrictParamName: 'Parameter name eval or arguments is not allowed in strict mode', + StrictReservedWord: 'Use of future reserved word in strict mode', + StrictVarName: 'Variable name may not be eval or arguments in strict mode', + TemplateOctalLiteral: 'Octal literals are not allowed in template strings.', + UnexpectedEOS: 'Unexpected end of input', + UnexpectedIdentifier: 'Unexpected identifier', + UnexpectedNumber: 'Unexpected number', + UnexpectedReserved: 'Unexpected reserved word', + UnexpectedString: 'Unexpected string', + UnexpectedTemplate: 'Unexpected quasi %0', + UnexpectedToken: 'Unexpected token %0', + UnexpectedTokenIllegal: 'Unexpected token ILLEGAL', + UnknownLabel: 'Undefined label \'%0\'', + UnterminatedRegExp: 'Invalid regular expression: missing /' + }; + + +/***/ }, +/* 12 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var assert_1 = __webpack_require__(9); + var character_1 = __webpack_require__(4); + var messages_1 = __webpack_require__(11); + function hexValue(ch) { + return '0123456789abcdef'.indexOf(ch.toLowerCase()); + } + function octalValue(ch) { + return '01234567'.indexOf(ch); + } + var Scanner = (function () { + function Scanner(code, handler) { + this.source = code; + this.errorHandler = handler; + this.trackComment = false; + this.length = code.length; + this.index = 0; + this.lineNumber = (code.length > 0) ? 1 : 0; + this.lineStart = 0; + this.curlyStack = []; + } + Scanner.prototype.saveState = function () { + return { + index: this.index, + lineNumber: this.lineNumber, + lineStart: this.lineStart + }; + }; + Scanner.prototype.restoreState = function (state) { + this.index = state.index; + this.lineNumber = state.lineNumber; + this.lineStart = state.lineStart; + }; + Scanner.prototype.eof = function () { + return this.index >= this.length; + }; + Scanner.prototype.throwUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + return this.errorHandler.throwError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + Scanner.prototype.tolerateUnexpectedToken = function (message) { + if (message === void 0) { message = messages_1.Messages.UnexpectedTokenIllegal; } + this.errorHandler.tolerateError(this.index, this.lineNumber, this.index - this.lineStart + 1, message); + }; + // https://tc39.github.io/ecma262/#sec-comments + Scanner.prototype.skipSingleLineComment = function (offset) { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - offset; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - offset + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + ++this.index; + if (character_1.Character.isLineTerminator(ch)) { + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart - 1 + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index - 1], + range: [start, this.index - 1], + loc: loc + }; + comments.push(entry); + } + if (ch === 13 && this.source.charCodeAt(this.index) === 10) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + return comments; + } + } + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: false, + slice: [start + offset, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + }; + Scanner.prototype.skipMultiLineComment = function () { + var comments = []; + var start, loc; + if (this.trackComment) { + comments = []; + start = this.index - 2; + loc = { + start: { + line: this.lineNumber, + column: this.index - this.lineStart - 2 + }, + end: {} + }; + } + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isLineTerminator(ch)) { + if (ch === 0x0D && this.source.charCodeAt(this.index + 1) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + ++this.index; + this.lineStart = this.index; + } + else if (ch === 0x2A) { + // Block comment ends with '*/'. + if (this.source.charCodeAt(this.index + 1) === 0x2F) { + this.index += 2; + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index - 2], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + return comments; + } + ++this.index; + } + else { + ++this.index; + } + } + // Ran off the end of the file - the whole thing is a comment + if (this.trackComment) { + loc.end = { + line: this.lineNumber, + column: this.index - this.lineStart + }; + var entry = { + multiLine: true, + slice: [start + 2, this.index], + range: [start, this.index], + loc: loc + }; + comments.push(entry); + } + this.tolerateUnexpectedToken(); + return comments; + }; + Scanner.prototype.scanComments = function () { + var comments; + if (this.trackComment) { + comments = []; + } + var start = (this.index === 0); + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (character_1.Character.isWhiteSpace(ch)) { + ++this.index; + } + else if (character_1.Character.isLineTerminator(ch)) { + ++this.index; + if (ch === 0x0D && this.source.charCodeAt(this.index) === 0x0A) { + ++this.index; + } + ++this.lineNumber; + this.lineStart = this.index; + start = true; + } + else if (ch === 0x2F) { + ch = this.source.charCodeAt(this.index + 1); + if (ch === 0x2F) { + this.index += 2; + var comment = this.skipSingleLineComment(2); + if (this.trackComment) { + comments = comments.concat(comment); + } + start = true; + } + else if (ch === 0x2A) { + this.index += 2; + var comment = this.skipMultiLineComment(); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (start && ch === 0x2D) { + // U+003E is '>' + if ((this.source.charCodeAt(this.index + 1) === 0x2D) && (this.source.charCodeAt(this.index + 2) === 0x3E)) { + // '-->' is a single-line comment + this.index += 3; + var comment = this.skipSingleLineComment(3); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else if (ch === 0x3C) { + if (this.source.slice(this.index + 1, this.index + 4) === '!--') { + this.index += 4; // `<!--` + var comment = this.skipSingleLineComment(4); + if (this.trackComment) { + comments = comments.concat(comment); + } + } + else { + break; + } + } + else { + break; + } + } + return comments; + }; + // https://tc39.github.io/ecma262/#sec-future-reserved-words + Scanner.prototype.isFutureReservedWord = function (id) { + switch (id) { + case 'enum': + case 'export': + case 'import': + case 'super': + return true; + default: + return false; + } + }; + Scanner.prototype.isStrictModeReservedWord = function (id) { + switch (id) { + case 'implements': + case 'interface': + case 'package': + case 'private': + case 'protected': + case 'public': + case 'static': + case 'yield': + case 'let': + return true; + default: + return false; + } + }; + Scanner.prototype.isRestrictedWord = function (id) { + return id === 'eval' || id === 'arguments'; + }; + // https://tc39.github.io/ecma262/#sec-keywords + Scanner.prototype.isKeyword = function (id) { + switch (id.length) { + case 2: + return (id === 'if') || (id === 'in') || (id === 'do'); + case 3: + return (id === 'var') || (id === 'for') || (id === 'new') || + (id === 'try') || (id === 'let'); + case 4: + return (id === 'this') || (id === 'else') || (id === 'case') || + (id === 'void') || (id === 'with') || (id === 'enum'); + case 5: + return (id === 'while') || (id === 'break') || (id === 'catch') || + (id === 'throw') || (id === 'const') || (id === 'yield') || + (id === 'class') || (id === 'super'); + case 6: + return (id === 'return') || (id === 'typeof') || (id === 'delete') || + (id === 'switch') || (id === 'export') || (id === 'import'); + case 7: + return (id === 'default') || (id === 'finally') || (id === 'extends'); + case 8: + return (id === 'function') || (id === 'continue') || (id === 'debugger'); + case 10: + return (id === 'instanceof'); + default: + return false; + } + }; + Scanner.prototype.codePointAt = function (i) { + var cp = this.source.charCodeAt(i); + if (cp >= 0xD800 && cp <= 0xDBFF) { + var second = this.source.charCodeAt(i + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + var first = cp; + cp = (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return cp; + }; + Scanner.prototype.scanHexEscape = function (prefix) { + var len = (prefix === 'u') ? 4 : 2; + var code = 0; + for (var i = 0; i < len; ++i) { + if (!this.eof() && character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { + code = code * 16 + hexValue(this.source[this.index++]); + } + else { + return null; + } + } + return String.fromCharCode(code); + }; + Scanner.prototype.scanUnicodeCodePointEscape = function () { + var ch = this.source[this.index]; + var code = 0; + // At least, one hex digit is required. + if (ch === '}') { + this.throwUnexpectedToken(); + } + while (!this.eof()) { + ch = this.source[this.index++]; + if (!character_1.Character.isHexDigit(ch.charCodeAt(0))) { + break; + } + code = code * 16 + hexValue(ch); + } + if (code > 0x10FFFF || ch !== '}') { + this.throwUnexpectedToken(); + } + return character_1.Character.fromCodePoint(code); + }; + Scanner.prototype.getIdentifier = function () { + var start = this.index++; + while (!this.eof()) { + var ch = this.source.charCodeAt(this.index); + if (ch === 0x5C) { + // Blackslash (U+005C) marks Unicode escape sequence. + this.index = start; + return this.getComplexIdentifier(); + } + else if (ch >= 0xD800 && ch < 0xDFFF) { + // Need to handle surrogate pairs. + this.index = start; + return this.getComplexIdentifier(); + } + if (character_1.Character.isIdentifierPart(ch)) { + ++this.index; + } + else { + break; + } + } + return this.source.slice(start, this.index); + }; + Scanner.prototype.getComplexIdentifier = function () { + var cp = this.codePointAt(this.index); + var id = character_1.Character.fromCodePoint(cp); + this.index += id.length; + // '\u' (U+005C, U+0075) denotes an escaped character. + var ch; + if (cp === 0x5C) { + if (this.source.charCodeAt(this.index) !== 0x75) { + this.throwUnexpectedToken(); + } + ++this.index; + if (this.source[this.index] === '{') { + ++this.index; + ch = this.scanUnicodeCodePointEscape(); + } + else { + ch = this.scanHexEscape('u'); + if (ch === null || ch === '\\' || !character_1.Character.isIdentifierStart(ch.charCodeAt(0))) { + this.throwUnexpectedToken(); + } + } + id = ch; + } + while (!this.eof()) { + cp = this.codePointAt(this.index); + if (!character_1.Character.isIdentifierPart(cp)) { + break; + } + ch = character_1.Character.fromCodePoint(cp); + id += ch; + this.index += ch.length; + // '\u' (U+005C, U+0075) denotes an escaped character. + if (cp === 0x5C) { + id = id.substr(0, id.length - 1); + if (this.source.charCodeAt(this.index) !== 0x75) { + this.throwUnexpectedToken(); + } + ++this.index; + if (this.source[this.index] === '{') { + ++this.index; + ch = this.scanUnicodeCodePointEscape(); + } + else { + ch = this.scanHexEscape('u'); + if (ch === null || ch === '\\' || !character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { + this.throwUnexpectedToken(); + } + } + id += ch; + } + } + return id; + }; + Scanner.prototype.octalToDecimal = function (ch) { + // \0 is not octal escape sequence + var octal = (ch !== '0'); + var code = octalValue(ch); + if (!this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + octal = true; + code = code * 8 + octalValue(this.source[this.index++]); + // 3 digits are only allowed when string starts + // with 0, 1, 2, 3 + if ('0123'.indexOf(ch) >= 0 && !this.eof() && character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + code = code * 8 + octalValue(this.source[this.index++]); + } + } + return { + code: code, + octal: octal + }; + }; + // https://tc39.github.io/ecma262/#sec-names-and-keywords + Scanner.prototype.scanIdentifier = function () { + var type; + var start = this.index; + // Backslash (U+005C) starts an escaped character. + var id = (this.source.charCodeAt(start) === 0x5C) ? this.getComplexIdentifier() : this.getIdentifier(); + // There is no keyword or literal with only one character. + // Thus, it must be an identifier. + if (id.length === 1) { + type = 3 /* Identifier */; + } + else if (this.isKeyword(id)) { + type = 4 /* Keyword */; + } + else if (id === 'null') { + type = 5 /* NullLiteral */; + } + else if (id === 'true' || id === 'false') { + type = 1 /* BooleanLiteral */; + } + else { + type = 3 /* Identifier */; + } + if (type !== 3 /* Identifier */ && (start + id.length !== this.index)) { + var restore = this.index; + this.index = start; + this.tolerateUnexpectedToken(messages_1.Messages.InvalidEscapedReservedWord); + this.index = restore; + } + return { + type: type, + value: id, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-punctuators + Scanner.prototype.scanPunctuator = function () { + var start = this.index; + // Check for most common single-character punctuators. + var str = this.source[this.index]; + switch (str) { + case '(': + case '{': + if (str === '{') { + this.curlyStack.push('{'); + } + ++this.index; + break; + case '.': + ++this.index; + if (this.source[this.index] === '.' && this.source[this.index + 1] === '.') { + // Spread operator: ... + this.index += 2; + str = '...'; + } + break; + case '}': + ++this.index; + this.curlyStack.pop(); + break; + case ')': + case ';': + case ',': + case '[': + case ']': + case ':': + case '?': + case '~': + ++this.index; + break; + default: + // 4-character punctuator. + str = this.source.substr(this.index, 4); + if (str === '>>>=') { + this.index += 4; + } + else { + // 3-character punctuators. + str = str.substr(0, 3); + if (str === '===' || str === '!==' || str === '>>>' || + str === '<<=' || str === '>>=' || str === '**=') { + this.index += 3; + } + else { + // 2-character punctuators. + str = str.substr(0, 2); + if (str === '&&' || str === '||' || str === '==' || str === '!=' || + str === '+=' || str === '-=' || str === '*=' || str === '/=' || + str === '++' || str === '--' || str === '<<' || str === '>>' || + str === '&=' || str === '|=' || str === '^=' || str === '%=' || + str === '<=' || str === '>=' || str === '=>' || str === '**') { + this.index += 2; + } + else { + // 1-character punctuators. + str = this.source[this.index]; + if ('<>=!+-*%&|^/'.indexOf(str) >= 0) { + ++this.index; + } + } + } + } + } + if (this.index === start) { + this.throwUnexpectedToken(); + } + return { + type: 7 /* Punctuator */, + value: str, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-numeric-literals + Scanner.prototype.scanHexLiteral = function (start) { + var num = ''; + while (!this.eof()) { + if (!character_1.Character.isHexDigit(this.source.charCodeAt(this.index))) { + break; + } + num += this.source[this.index++]; + } + if (num.length === 0) { + this.throwUnexpectedToken(); + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseInt('0x' + num, 16), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.scanBinaryLiteral = function (start) { + var num = ''; + var ch; + while (!this.eof()) { + ch = this.source[this.index]; + if (ch !== '0' && ch !== '1') { + break; + } + num += this.source[this.index++]; + } + if (num.length === 0) { + // only 0b or 0B + this.throwUnexpectedToken(); + } + if (!this.eof()) { + ch = this.source.charCodeAt(this.index); + /* istanbul ignore else */ + if (character_1.Character.isIdentifierStart(ch) || character_1.Character.isDecimalDigit(ch)) { + this.throwUnexpectedToken(); + } + } + return { + type: 6 /* NumericLiteral */, + value: parseInt(num, 2), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.scanOctalLiteral = function (prefix, start) { + var num = ''; + var octal = false; + if (character_1.Character.isOctalDigit(prefix.charCodeAt(0))) { + octal = true; + num = '0' + this.source[this.index++]; + } + else { + ++this.index; + } + while (!this.eof()) { + if (!character_1.Character.isOctalDigit(this.source.charCodeAt(this.index))) { + break; + } + num += this.source[this.index++]; + } + if (!octal && num.length === 0) { + // only 0o or 0O + this.throwUnexpectedToken(); + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index)) || character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseInt(num, 8), + octal: octal, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.isImplicitOctalLiteral = function () { + // Implicit octal, unless there is a non-octal digit. + // (Annex B.1.1 on Numeric Literals) + for (var i = this.index + 1; i < this.length; ++i) { + var ch = this.source[i]; + if (ch === '8' || ch === '9') { + return false; + } + if (!character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + return true; + } + } + return true; + }; + Scanner.prototype.scanNumericLiteral = function () { + var start = this.index; + var ch = this.source[start]; + assert_1.assert(character_1.Character.isDecimalDigit(ch.charCodeAt(0)) || (ch === '.'), 'Numeric literal must start with a decimal digit or a decimal point'); + var num = ''; + if (ch !== '.') { + num = this.source[this.index++]; + ch = this.source[this.index]; + // Hex number starts with '0x'. + // Octal number starts with '0'. + // Octal number in ES6 starts with '0o'. + // Binary number in ES6 starts with '0b'. + if (num === '0') { + if (ch === 'x' || ch === 'X') { + ++this.index; + return this.scanHexLiteral(start); + } + if (ch === 'b' || ch === 'B') { + ++this.index; + return this.scanBinaryLiteral(start); + } + if (ch === 'o' || ch === 'O') { + return this.scanOctalLiteral(ch, start); + } + if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + if (this.isImplicitOctalLiteral()) { + return this.scanOctalLiteral(ch, start); + } + } + } + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + ch = this.source[this.index]; + } + if (ch === '.') { + num += this.source[this.index++]; + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + ch = this.source[this.index]; + } + if (ch === 'e' || ch === 'E') { + num += this.source[this.index++]; + ch = this.source[this.index]; + if (ch === '+' || ch === '-') { + num += this.source[this.index++]; + } + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + while (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + num += this.source[this.index++]; + } + } + else { + this.throwUnexpectedToken(); + } + } + if (character_1.Character.isIdentifierStart(this.source.charCodeAt(this.index))) { + this.throwUnexpectedToken(); + } + return { + type: 6 /* NumericLiteral */, + value: parseFloat(num), + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-string-literals + Scanner.prototype.scanStringLiteral = function () { + var start = this.index; + var quote = this.source[start]; + assert_1.assert((quote === '\'' || quote === '"'), 'String literal must starts with a quote'); + ++this.index; + var octal = false; + var str = ''; + while (!this.eof()) { + var ch = this.source[this.index++]; + if (ch === quote) { + quote = ''; + break; + } + else if (ch === '\\') { + ch = this.source[this.index++]; + if (!ch || !character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'u': + if (this.source[this.index] === '{') { + ++this.index; + str += this.scanUnicodeCodePointEscape(); + } + else { + var unescaped_1 = this.scanHexEscape(ch); + if (unescaped_1 === null) { + this.throwUnexpectedToken(); + } + str += unescaped_1; + } + break; + case 'x': + var unescaped = this.scanHexEscape(ch); + if (unescaped === null) { + this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); + } + str += unescaped; + break; + case 'n': + str += '\n'; + break; + case 'r': + str += '\r'; + break; + case 't': + str += '\t'; + break; + case 'b': + str += '\b'; + break; + case 'f': + str += '\f'; + break; + case 'v': + str += '\x0B'; + break; + case '8': + case '9': + str += ch; + this.tolerateUnexpectedToken(); + break; + default: + if (ch && character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + var octToDec = this.octalToDecimal(ch); + octal = octToDec.octal || octal; + str += String.fromCharCode(octToDec.code); + } + else { + str += ch; + } + break; + } + } + else { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + } + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + break; + } + else { + str += ch; + } + } + if (quote !== '') { + this.index = start; + this.throwUnexpectedToken(); + } + return { + type: 8 /* StringLiteral */, + value: str, + octal: octal, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-template-literal-lexical-components + Scanner.prototype.scanTemplate = function () { + var cooked = ''; + var terminated = false; + var start = this.index; + var head = (this.source[start] === '`'); + var tail = false; + var rawOffset = 2; + ++this.index; + while (!this.eof()) { + var ch = this.source[this.index++]; + if (ch === '`') { + rawOffset = 1; + tail = true; + terminated = true; + break; + } + else if (ch === '$') { + if (this.source[this.index] === '{') { + this.curlyStack.push('${'); + ++this.index; + terminated = true; + break; + } + cooked += ch; + } + else if (ch === '\\') { + ch = this.source[this.index++]; + if (!character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + switch (ch) { + case 'n': + cooked += '\n'; + break; + case 'r': + cooked += '\r'; + break; + case 't': + cooked += '\t'; + break; + case 'u': + if (this.source[this.index] === '{') { + ++this.index; + cooked += this.scanUnicodeCodePointEscape(); + } + else { + var restore = this.index; + var unescaped_2 = this.scanHexEscape(ch); + if (unescaped_2 !== null) { + cooked += unescaped_2; + } + else { + this.index = restore; + cooked += ch; + } + } + break; + case 'x': + var unescaped = this.scanHexEscape(ch); + if (unescaped === null) { + this.throwUnexpectedToken(messages_1.Messages.InvalidHexEscapeSequence); + } + cooked += unescaped; + break; + case 'b': + cooked += '\b'; + break; + case 'f': + cooked += '\f'; + break; + case 'v': + cooked += '\v'; + break; + default: + if (ch === '0') { + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index))) { + // Illegal: \01 \02 and so on + this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); + } + cooked += '\0'; + } + else if (character_1.Character.isOctalDigit(ch.charCodeAt(0))) { + // Illegal: \1 \2 + this.throwUnexpectedToken(messages_1.Messages.TemplateOctalLiteral); + } + else { + cooked += ch; + } + break; + } + } + else { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + } + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + ++this.lineNumber; + if (ch === '\r' && this.source[this.index] === '\n') { + ++this.index; + } + this.lineStart = this.index; + cooked += '\n'; + } + else { + cooked += ch; + } + } + if (!terminated) { + this.throwUnexpectedToken(); + } + if (!head) { + this.curlyStack.pop(); + } + return { + type: 10 /* Template */, + value: this.source.slice(start + 1, this.index - rawOffset), + cooked: cooked, + head: head, + tail: tail, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals + Scanner.prototype.testRegExp = function (pattern, flags) { + // The BMP character to use as a replacement for astral symbols when + // translating an ES6 "u"-flagged pattern to an ES5-compatible + // approximation. + // Note: replacing with '\uFFFF' enables false positives in unlikely + // scenarios. For example, `[\u{1044f}-\u{10440}]` is an invalid + // pattern that would not be detected by this substitution. + var astralSubstitute = '\uFFFF'; + var tmp = pattern; + var self = this; + if (flags.indexOf('u') >= 0) { + tmp = tmp + .replace(/\\u\{([0-9a-fA-F]+)\}|\\u([a-fA-F0-9]{4})/g, function ($0, $1, $2) { + var codePoint = parseInt($1 || $2, 16); + if (codePoint > 0x10FFFF) { + self.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); + } + if (codePoint <= 0xFFFF) { + return String.fromCharCode(codePoint); + } + return astralSubstitute; + }) + .replace(/[\uD800-\uDBFF][\uDC00-\uDFFF]/g, astralSubstitute); + } + // First, detect invalid regular expressions. + try { + RegExp(tmp); + } + catch (e) { + this.throwUnexpectedToken(messages_1.Messages.InvalidRegExp); + } + // Return a regular expression object for this pattern-flag pair, or + // `null` in case the current environment doesn't support the flags it + // uses. + try { + return new RegExp(pattern, flags); + } + catch (exception) { + /* istanbul ignore next */ + return null; + } + }; + Scanner.prototype.scanRegExpBody = function () { + var ch = this.source[this.index]; + assert_1.assert(ch === '/', 'Regular expression literal must start with a slash'); + var str = this.source[this.index++]; + var classMarker = false; + var terminated = false; + while (!this.eof()) { + ch = this.source[this.index++]; + str += ch; + if (ch === '\\') { + ch = this.source[this.index++]; + // https://tc39.github.io/ecma262/#sec-literals-regular-expression-literals + if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + str += ch; + } + else if (character_1.Character.isLineTerminator(ch.charCodeAt(0))) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + else if (classMarker) { + if (ch === ']') { + classMarker = false; + } + } + else { + if (ch === '/') { + terminated = true; + break; + } + else if (ch === '[') { + classMarker = true; + } + } + } + if (!terminated) { + this.throwUnexpectedToken(messages_1.Messages.UnterminatedRegExp); + } + // Exclude leading and trailing slash. + return str.substr(1, str.length - 2); + }; + Scanner.prototype.scanRegExpFlags = function () { + var str = ''; + var flags = ''; + while (!this.eof()) { + var ch = this.source[this.index]; + if (!character_1.Character.isIdentifierPart(ch.charCodeAt(0))) { + break; + } + ++this.index; + if (ch === '\\' && !this.eof()) { + ch = this.source[this.index]; + if (ch === 'u') { + ++this.index; + var restore = this.index; + var char = this.scanHexEscape('u'); + if (char !== null) { + flags += char; + for (str += '\\u'; restore < this.index; ++restore) { + str += this.source[restore]; + } + } + else { + this.index = restore; + flags += 'u'; + str += '\\u'; + } + this.tolerateUnexpectedToken(); + } + else { + str += '\\'; + this.tolerateUnexpectedToken(); + } + } + else { + flags += ch; + str += ch; + } + } + return flags; + }; + Scanner.prototype.scanRegExp = function () { + var start = this.index; + var pattern = this.scanRegExpBody(); + var flags = this.scanRegExpFlags(); + var value = this.testRegExp(pattern, flags); + return { + type: 9 /* RegularExpression */, + value: '', + pattern: pattern, + flags: flags, + regex: value, + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: start, + end: this.index + }; + }; + Scanner.prototype.lex = function () { + if (this.eof()) { + return { + type: 2 /* EOF */, + value: '', + lineNumber: this.lineNumber, + lineStart: this.lineStart, + start: this.index, + end: this.index + }; + } + var cp = this.source.charCodeAt(this.index); + if (character_1.Character.isIdentifierStart(cp)) { + return this.scanIdentifier(); + } + // Very common: ( and ) and ; + if (cp === 0x28 || cp === 0x29 || cp === 0x3B) { + return this.scanPunctuator(); + } + // String literal starts with single quote (U+0027) or double quote (U+0022). + if (cp === 0x27 || cp === 0x22) { + return this.scanStringLiteral(); + } + // Dot (.) U+002E can also start a floating-point number, hence the need + // to check the next character. + if (cp === 0x2E) { + if (character_1.Character.isDecimalDigit(this.source.charCodeAt(this.index + 1))) { + return this.scanNumericLiteral(); + } + return this.scanPunctuator(); + } + if (character_1.Character.isDecimalDigit(cp)) { + return this.scanNumericLiteral(); + } + // Template literals start with ` (U+0060) for template head + // or } (U+007D) for template middle or template tail. + if (cp === 0x60 || (cp === 0x7D && this.curlyStack[this.curlyStack.length - 1] === '${')) { + return this.scanTemplate(); + } + // Possible identifier start in a surrogate pair. + if (cp >= 0xD800 && cp < 0xDFFF) { + if (character_1.Character.isIdentifierStart(this.codePointAt(this.index))) { + return this.scanIdentifier(); + } + } + return this.scanPunctuator(); + }; + return Scanner; + }()); + exports.Scanner = Scanner; + + +/***/ }, +/* 13 */ +/***/ function(module, exports) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + exports.TokenName = {}; + exports.TokenName[1 /* BooleanLiteral */] = 'Boolean'; + exports.TokenName[2 /* EOF */] = '<end>'; + exports.TokenName[3 /* Identifier */] = 'Identifier'; + exports.TokenName[4 /* Keyword */] = 'Keyword'; + exports.TokenName[5 /* NullLiteral */] = 'Null'; + exports.TokenName[6 /* NumericLiteral */] = 'Numeric'; + exports.TokenName[7 /* Punctuator */] = 'Punctuator'; + exports.TokenName[8 /* StringLiteral */] = 'String'; + exports.TokenName[9 /* RegularExpression */] = 'RegularExpression'; + exports.TokenName[10 /* Template */] = 'Template'; + + +/***/ }, +/* 14 */ +/***/ function(module, exports) { + + "use strict"; + // Generated by generate-xhtml-entities.js. DO NOT MODIFY! + Object.defineProperty(exports, "__esModule", { value: true }); + exports.XHTMLEntities = { + quot: '\u0022', + amp: '\u0026', + apos: '\u0027', + gt: '\u003E', + nbsp: '\u00A0', + iexcl: '\u00A1', + cent: '\u00A2', + pound: '\u00A3', + curren: '\u00A4', + yen: '\u00A5', + brvbar: '\u00A6', + sect: '\u00A7', + uml: '\u00A8', + copy: '\u00A9', + ordf: '\u00AA', + laquo: '\u00AB', + not: '\u00AC', + shy: '\u00AD', + reg: '\u00AE', + macr: '\u00AF', + deg: '\u00B0', + plusmn: '\u00B1', + sup2: '\u00B2', + sup3: '\u00B3', + acute: '\u00B4', + micro: '\u00B5', + para: '\u00B6', + middot: '\u00B7', + cedil: '\u00B8', + sup1: '\u00B9', + ordm: '\u00BA', + raquo: '\u00BB', + frac14: '\u00BC', + frac12: '\u00BD', + frac34: '\u00BE', + iquest: '\u00BF', + Agrave: '\u00C0', + Aacute: '\u00C1', + Acirc: '\u00C2', + Atilde: '\u00C3', + Auml: '\u00C4', + Aring: '\u00C5', + AElig: '\u00C6', + Ccedil: '\u00C7', + Egrave: '\u00C8', + Eacute: '\u00C9', + Ecirc: '\u00CA', + Euml: '\u00CB', + Igrave: '\u00CC', + Iacute: '\u00CD', + Icirc: '\u00CE', + Iuml: '\u00CF', + ETH: '\u00D0', + Ntilde: '\u00D1', + Ograve: '\u00D2', + Oacute: '\u00D3', + Ocirc: '\u00D4', + Otilde: '\u00D5', + Ouml: '\u00D6', + times: '\u00D7', + Oslash: '\u00D8', + Ugrave: '\u00D9', + Uacute: '\u00DA', + Ucirc: '\u00DB', + Uuml: '\u00DC', + Yacute: '\u00DD', + THORN: '\u00DE', + szlig: '\u00DF', + agrave: '\u00E0', + aacute: '\u00E1', + acirc: '\u00E2', + atilde: '\u00E3', + auml: '\u00E4', + aring: '\u00E5', + aelig: '\u00E6', + ccedil: '\u00E7', + egrave: '\u00E8', + eacute: '\u00E9', + ecirc: '\u00EA', + euml: '\u00EB', + igrave: '\u00EC', + iacute: '\u00ED', + icirc: '\u00EE', + iuml: '\u00EF', + eth: '\u00F0', + ntilde: '\u00F1', + ograve: '\u00F2', + oacute: '\u00F3', + ocirc: '\u00F4', + otilde: '\u00F5', + ouml: '\u00F6', + divide: '\u00F7', + oslash: '\u00F8', + ugrave: '\u00F9', + uacute: '\u00FA', + ucirc: '\u00FB', + uuml: '\u00FC', + yacute: '\u00FD', + thorn: '\u00FE', + yuml: '\u00FF', + OElig: '\u0152', + oelig: '\u0153', + Scaron: '\u0160', + scaron: '\u0161', + Yuml: '\u0178', + fnof: '\u0192', + circ: '\u02C6', + tilde: '\u02DC', + Alpha: '\u0391', + Beta: '\u0392', + Gamma: '\u0393', + Delta: '\u0394', + Epsilon: '\u0395', + Zeta: '\u0396', + Eta: '\u0397', + Theta: '\u0398', + Iota: '\u0399', + Kappa: '\u039A', + Lambda: '\u039B', + Mu: '\u039C', + Nu: '\u039D', + Xi: '\u039E', + Omicron: '\u039F', + Pi: '\u03A0', + Rho: '\u03A1', + Sigma: '\u03A3', + Tau: '\u03A4', + Upsilon: '\u03A5', + Phi: '\u03A6', + Chi: '\u03A7', + Psi: '\u03A8', + Omega: '\u03A9', + alpha: '\u03B1', + beta: '\u03B2', + gamma: '\u03B3', + delta: '\u03B4', + epsilon: '\u03B5', + zeta: '\u03B6', + eta: '\u03B7', + theta: '\u03B8', + iota: '\u03B9', + kappa: '\u03BA', + lambda: '\u03BB', + mu: '\u03BC', + nu: '\u03BD', + xi: '\u03BE', + omicron: '\u03BF', + pi: '\u03C0', + rho: '\u03C1', + sigmaf: '\u03C2', + sigma: '\u03C3', + tau: '\u03C4', + upsilon: '\u03C5', + phi: '\u03C6', + chi: '\u03C7', + psi: '\u03C8', + omega: '\u03C9', + thetasym: '\u03D1', + upsih: '\u03D2', + piv: '\u03D6', + ensp: '\u2002', + emsp: '\u2003', + thinsp: '\u2009', + zwnj: '\u200C', + zwj: '\u200D', + lrm: '\u200E', + rlm: '\u200F', + ndash: '\u2013', + mdash: '\u2014', + lsquo: '\u2018', + rsquo: '\u2019', + sbquo: '\u201A', + ldquo: '\u201C', + rdquo: '\u201D', + bdquo: '\u201E', + dagger: '\u2020', + Dagger: '\u2021', + bull: '\u2022', + hellip: '\u2026', + permil: '\u2030', + prime: '\u2032', + Prime: '\u2033', + lsaquo: '\u2039', + rsaquo: '\u203A', + oline: '\u203E', + frasl: '\u2044', + euro: '\u20AC', + image: '\u2111', + weierp: '\u2118', + real: '\u211C', + trade: '\u2122', + alefsym: '\u2135', + larr: '\u2190', + uarr: '\u2191', + rarr: '\u2192', + darr: '\u2193', + harr: '\u2194', + crarr: '\u21B5', + lArr: '\u21D0', + uArr: '\u21D1', + rArr: '\u21D2', + dArr: '\u21D3', + hArr: '\u21D4', + forall: '\u2200', + part: '\u2202', + exist: '\u2203', + empty: '\u2205', + nabla: '\u2207', + isin: '\u2208', + notin: '\u2209', + ni: '\u220B', + prod: '\u220F', + sum: '\u2211', + minus: '\u2212', + lowast: '\u2217', + radic: '\u221A', + prop: '\u221D', + infin: '\u221E', + ang: '\u2220', + and: '\u2227', + or: '\u2228', + cap: '\u2229', + cup: '\u222A', + int: '\u222B', + there4: '\u2234', + sim: '\u223C', + cong: '\u2245', + asymp: '\u2248', + ne: '\u2260', + equiv: '\u2261', + le: '\u2264', + ge: '\u2265', + sub: '\u2282', + sup: '\u2283', + nsub: '\u2284', + sube: '\u2286', + supe: '\u2287', + oplus: '\u2295', + otimes: '\u2297', + perp: '\u22A5', + sdot: '\u22C5', + lceil: '\u2308', + rceil: '\u2309', + lfloor: '\u230A', + rfloor: '\u230B', + loz: '\u25CA', + spades: '\u2660', + clubs: '\u2663', + hearts: '\u2665', + diams: '\u2666', + lang: '\u27E8', + rang: '\u27E9' + }; + + +/***/ }, +/* 15 */ +/***/ function(module, exports, __webpack_require__) { + + "use strict"; + Object.defineProperty(exports, "__esModule", { value: true }); + var error_handler_1 = __webpack_require__(10); + var scanner_1 = __webpack_require__(12); + var token_1 = __webpack_require__(13); + var Reader = (function () { + function Reader() { + this.values = []; + this.curly = this.paren = -1; + } + // A function following one of those tokens is an expression. + Reader.prototype.beforeFunctionExpression = function (t) { + return ['(', '{', '[', 'in', 'typeof', 'instanceof', 'new', + 'return', 'case', 'delete', 'throw', 'void', + // assignment operators + '=', '+=', '-=', '*=', '**=', '/=', '%=', '<<=', '>>=', '>>>=', + '&=', '|=', '^=', ',', + // binary/unary operators + '+', '-', '*', '**', '/', '%', '++', '--', '<<', '>>', '>>>', '&', + '|', '^', '!', '~', '&&', '||', '?', ':', '===', '==', '>=', + '<=', '<', '>', '!=', '!=='].indexOf(t) >= 0; + }; + // Determine if forward slash (/) is an operator or part of a regular expression + // https://github.com/mozilla/sweet.js/wiki/design + Reader.prototype.isRegexStart = function () { + var previous = this.values[this.values.length - 1]; + var regex = (previous !== null); + switch (previous) { + case 'this': + case ']': + regex = false; + break; + case ')': + var keyword = this.values[this.paren - 1]; + regex = (keyword === 'if' || keyword === 'while' || keyword === 'for' || keyword === 'with'); + break; + case '}': + // Dividing a function by anything makes little sense, + // but we have to check for that. + regex = false; + if (this.values[this.curly - 3] === 'function') { + // Anonymous function, e.g. function(){} /42 + var check = this.values[this.curly - 4]; + regex = check ? !this.beforeFunctionExpression(check) : false; + } + else if (this.values[this.curly - 4] === 'function') { + // Named function, e.g. function f(){} /42/ + var check = this.values[this.curly - 5]; + regex = check ? !this.beforeFunctionExpression(check) : true; + } + break; + default: + break; + } + return regex; + }; + Reader.prototype.push = function (token) { + if (token.type === 7 /* Punctuator */ || token.type === 4 /* Keyword */) { + if (token.value === '{') { + this.curly = this.values.length; + } + else if (token.value === '(') { + this.paren = this.values.length; + } + this.values.push(token.value); + } + else { + this.values.push(null); + } + }; + return Reader; + }()); + var Tokenizer = (function () { + function Tokenizer(code, config) { + this.errorHandler = new error_handler_1.ErrorHandler(); + this.errorHandler.tolerant = config ? (typeof config.tolerant === 'boolean' && config.tolerant) : false; + this.scanner = new scanner_1.Scanner(code, this.errorHandler); + this.scanner.trackComment = config ? (typeof config.comment === 'boolean' && config.comment) : false; + this.trackRange = config ? (typeof config.range === 'boolean' && config.range) : false; + this.trackLoc = config ? (typeof config.loc === 'boolean' && config.loc) : false; + this.buffer = []; + this.reader = new Reader(); + } + Tokenizer.prototype.errors = function () { + return this.errorHandler.errors; + }; + Tokenizer.prototype.getNextToken = function () { + if (this.buffer.length === 0) { + var comments = this.scanner.scanComments(); + if (this.scanner.trackComment) { + for (var i = 0; i < comments.length; ++i) { + var e = comments[i]; + var value = this.scanner.source.slice(e.slice[0], e.slice[1]); + var comment = { + type: e.multiLine ? 'BlockComment' : 'LineComment', + value: value + }; + if (this.trackRange) { + comment.range = e.range; + } + if (this.trackLoc) { + comment.loc = e.loc; + } + this.buffer.push(comment); + } + } + if (!this.scanner.eof()) { + var loc = void 0; + if (this.trackLoc) { + loc = { + start: { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }, + end: {} + }; + } + var startRegex = (this.scanner.source[this.scanner.index] === '/') && this.reader.isRegexStart(); + var token = startRegex ? this.scanner.scanRegExp() : this.scanner.lex(); + this.reader.push(token); + var entry = { + type: token_1.TokenName[token.type], + value: this.scanner.source.slice(token.start, token.end) + }; + if (this.trackRange) { + entry.range = [token.start, token.end]; + } + if (this.trackLoc) { + loc.end = { + line: this.scanner.lineNumber, + column: this.scanner.index - this.scanner.lineStart + }; + entry.loc = loc; + } + if (token.type === 9 /* RegularExpression */) { + var pattern = token.pattern; + var flags = token.flags; + entry.regex = { pattern: pattern, flags: flags }; + } + this.buffer.push(entry); + } + } + return this.buffer.shift(); + }; + return Tokenizer; + }()); + exports.Tokenizer = Tokenizer; + + +/***/ } +/******/ ]) +}); +; +/*global define, Reflect */ + +/* + * xpcshell has a smaller stack on linux and windows (1MB vs 9MB on mac), + * and the recursive nature of esprima can cause it to overflow pretty + * quickly. So favor it built in Reflect parser: + * https://developer.mozilla.org/en-US/docs/SpiderMonkey/Parser_API + */ +define('esprimaAdapter', ['./esprima', 'env'], function (esprima, env) { + if (env.get() === 'xpconnect' && typeof Reflect !== 'undefined') { + return Reflect; + } else { + return esprima; + } +}); +(function webpackUniversalModuleDefinition(root, factory) { +var exports, module; + if(typeof exports === 'object' && typeof module === 'object') + module.exports = factory(); + else if(typeof define === 'function' && define.amd) + define('source-map', [], factory); + else if(typeof exports === 'object') + exports["sourceMap"] = factory(); + else + root["sourceMap"] = factory(); +})(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__) { + + /* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ + exports.SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + exports.SourceMapConsumer = __webpack_require__(7).SourceMapConsumer; + exports.SourceNode = __webpack_require__(10).SourceNode; + + +/***/ }, +/* 1 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var base64VLQ = __webpack_require__(2); + var util = __webpack_require__(4); + var ArraySet = __webpack_require__(5).ArraySet; + var MappingList = __webpack_require__(6).MappingList; + + /** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ + function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; + } + + SourceMapGenerator.prototype._version = 3; + + /** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ + SourceMapGenerator.fromSourceMap = + function SourceMapGenerator_fromSourceMap(aSourceMapConsumer) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator({ + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot + }); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn + } + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; + }; + + /** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ + SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + this._validateMapping(generated, original, source, name); + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name + }); + }; + + /** + * Set the source content for a source file. + */ + SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + + /** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ + SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap(aSourceMapConsumer, aSourceFile, aSourceMapPath) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source) + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + + /** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ + SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping(aGenerated, aOriginal, aSource, + aName) { + if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aGenerated.line > 0 && aGenerated.column >= 0 + && !aOriginal && !aSource && !aName) { + // Case 1. + return; + } + else if (aGenerated && 'line' in aGenerated && 'column' in aGenerated + && aOriginal && 'line' in aOriginal && 'column' in aOriginal + && aGenerated.line > 0 && aGenerated.column >= 0 + && aOriginal.line > 0 && aOriginal.column >= 0 + && aSource) { + // Cases 2 and 3. + return; + } + else { + throw new Error('Invalid mapping: ' + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName + })); + } + }; + + /** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ + SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = '' + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + while (mapping.generatedLine !== previousGeneratedLine) { + next += ';'; + previousGeneratedLine++; + } + } + else { + if (i > 0) { + if (!util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1])) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode(mapping.generatedColumn + - previousGeneratedColumn); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode(mapping.originalLine - 1 + - previousOriginalLine); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode(mapping.originalColumn + - previousOriginalColumn); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + + SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + + /** + * Externalize the source map. + */ + SourceMapGenerator.prototype.toJSON = + function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings() + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent(map.sources, map.sourceRoot); + } + + return map; + }; + + /** + * Render the source map being generated to a string. + */ + SourceMapGenerator.prototype.toString = + function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); + }; + + exports.SourceMapGenerator = SourceMapGenerator; + + +/***/ }, +/* 2 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. 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 Google 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. + */ + + var base64 = __webpack_require__(3); + + // A single base 64 digit can contain 6 bits of data. For the base 64 variable + // length quantities we use in the source map spec, the first bit is the sign, + // the next four bits are the actual value, and the 6th bit is the + // continuation bit. The continuation bit tells us whether there are more + // digits in this value following this digit. + // + // Continuation + // | Sign + // | | + // V V + // 101011 + + var VLQ_BASE_SHIFT = 5; + + // binary: 100000 + var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + + // binary: 011111 + var VLQ_BASE_MASK = VLQ_BASE - 1; + + // binary: 100000 + var VLQ_CONTINUATION_BIT = VLQ_BASE; + + /** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ + function toVLQSigned(aValue) { + return aValue < 0 + ? ((-aValue) << 1) + 1 + : (aValue << 1) + 0; + } + + /** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ + function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative + ? -shifted + : shifted; + } + + /** + * Returns the base 64 VLQ encoded value. + */ + exports.encode = function base64VLQ_encode(aValue) { + var encoded = ""; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; + }; + + /** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ + exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error("Expected more digits in base 64 VLQ value."); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error("Invalid base64 digit: " + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; + }; + + +/***/ }, +/* 3 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var intToCharMap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + + /** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ + exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError("Must be between 0 and 63: " + number); + }; + + /** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ + exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return (charCode - bigA); + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return (charCode - littleA + littleOffset); + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return (charCode - zero + numberOffset); + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; + }; + + +/***/ }, +/* 4 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + /** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ + function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } + } + exports.getArg = getArg; + + var urlRegexp = /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.]*)(?::(\d+))?(\S*)$/; + var dataUrlRegexp = /^data:.+\,.+$/; + + function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5] + }; + } + exports.urlParse = urlParse; + + function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ":" + aParsedUrl.port + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; + } + exports.urlGenerate = urlGenerate; + + /** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consequtive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '<dir>/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ + function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + + var parts = path.split(/\/+/); + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; + } + exports.normalize = normalize; + + /** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ + function join(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + if (aPath === "") { + aPath = "."; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; + } + exports.join = join; + + exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || !!aPath.match(urlRegexp); + }; + + /** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ + function relative(aRoot, aPath) { + if (aRoot === "") { + aRoot = "."; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf("/"); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join("../") + aPath.substr(aRoot.length + 1); + } + exports.relative = relative; + + var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); + }()); + + function identity (s) { + return s; + } + + /** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ + function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; + } + exports.toSetString = supportsNullProto ? identity : toSetString; + + function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; + } + exports.fromSetString = supportsNullProto ? identity : fromSetString; + + function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if (s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; + } + + /** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ + function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByOriginalPositions = compareByOriginalPositions; + + /** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ + function compareByGeneratedPositionsDeflated(mappingA, mappingB, onlyCompareGenerated) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = mappingA.source - mappingB.source; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return mappingA.name - mappingB.name; + } + exports.compareByGeneratedPositionsDeflated = compareByGeneratedPositionsDeflated; + + function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; + } + + /** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ + function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); + } + exports.compareByGeneratedPositionsInflated = compareByGeneratedPositionsInflated; + + +/***/ }, +/* 5 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var has = Object.prototype.hasOwnProperty; + + /** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ + function ArraySet() { + this._array = []; + this._set = Object.create(null); + } + + /** + * Static method for creating ArraySet instances from an existing array. + */ + ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; + }; + + /** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ + ArraySet.prototype.size = function ArraySet_size() { + return Object.getOwnPropertyNames(this._set).length; + }; + + /** + * Add the given string to this set. + * + * @param String aStr + */ + ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = util.toSetString(aStr); + var isDuplicate = has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + this._set[sStr] = idx; + } + }; + + /** + * Is the given string a member of this set? + * + * @param String aStr + */ + ArraySet.prototype.has = function ArraySet_has(aStr) { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + }; + + /** + * What is the index of the given string in the array? + * + * @param String aStr + */ + ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + throw new Error('"' + aStr + '" is not in the set.'); + }; + + /** + * What is the element at the given index? + * + * @param Number aIdx + */ + ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); + }; + + /** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ + ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); + }; + + exports.ArraySet = ArraySet; + + +/***/ }, +/* 6 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + + /** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ + function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return lineB > lineA || lineB == lineA && columnB >= columnA || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0; + } + + /** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ + function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = {generatedLine: -1, generatedColumn: 0}; + } + + /** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ + MappingList.prototype.unsortedForEach = + function MappingList_forEach(aCallback, aThisArg) { + this._array.forEach(aCallback, aThisArg); + }; + + /** + * Add the given source mapping. + * + * @param Object aMapping + */ + MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } + }; + + /** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ + MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; + }; + + exports.MappingList = MappingList; + + +/***/ }, +/* 7 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var util = __webpack_require__(4); + var binarySearch = __webpack_require__(8); + var ArraySet = __webpack_require__(5).ArraySet; + var base64VLQ = __webpack_require__(2); + var quickSort = __webpack_require__(9).quickSort; + + function SourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap) + : new BasicSourceMapConsumer(sourceMap); + } + + SourceMapConsumer.fromSourceMap = function(aSourceMap) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap); + } + + /** + * The version of the source mapping spec that we are consuming. + */ + SourceMapConsumer.prototype._version = 3; + + // `__generatedMappings` and `__originalMappings` are arrays that hold the + // parsed mapping coordinates from the source map's "mappings" attribute. They + // are lazily instantiated, accessed via the `_generatedMappings` and + // `_originalMappings` getters respectively, and we only parse the mappings + // and create these arrays once queried for a source location. We jump through + // these hoops because there can be many thousands of mappings, and parsing + // them is expensive, so we only want to do it if we must. + // + // Each object in the arrays is of the form: + // + // { + // generatedLine: The line number in the generated code, + // generatedColumn: The column number in the generated code, + // source: The path to the original source file that generated this + // chunk of code, + // originalLine: The line number in the original source that + // corresponds to this chunk of generated code, + // originalColumn: The column number in the original source that + // corresponds to this chunk of generated code, + // name: The name of the original symbol which generated this chunk of + // code. + // } + // + // All properties except for `generatedLine` and `generatedColumn` can be + // `null`. + // + // `_generatedMappings` is ordered by the generated positions. + // + // `_originalMappings` is ordered by the original positions. + + SourceMapConsumer.prototype.__generatedMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + } + }); + + SourceMapConsumer.prototype.__originalMappings = null; + Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + } + }); + + SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ";" || c === ","; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error("Subclasses must implement _parseMappings"); + }; + + SourceMapConsumer.GENERATED_ORDER = 1; + SourceMapConsumer.ORIGINAL_ORDER = 2; + + SourceMapConsumer.GREATEST_LOWER_BOUND = 1; + SourceMapConsumer.LEAST_UPPER_BOUND = 2; + + /** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ + SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error("Unknown order of iteration."); + } + + var sourceRoot = this.sourceRoot; + mappings.map(function (mapping) { + var source = mapping.source === null ? null : this._sources.at(mapping.source); + if (source != null && sourceRoot != null) { + source = util.join(sourceRoot, source); + } + return { + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : this._names.at(mapping.name) + }; + }, this).forEach(aCallback, context); + }; + + /** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: Optional. the column number in the original source. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0) + }; + + if (this.sourceRoot != null) { + needle.source = util.relative(this.sourceRoot, needle.source); + } + if (!this._sources.has(needle.source)) { + return []; + } + needle.source = this._sources.indexOf(needle.source); + + var mappings = []; + + var index = this._findMapping(needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we found. Since + // mappings are sorted, this is guaranteed to find all mappings for + // the line we found. + while (mapping && mapping.originalLine === originalLine) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different line than the one we were searching for. + // Since mappings are sorted, this is guaranteed to find all mappings for + // the line we are searching for. + while (mapping && + mapping.originalLine === line && + mapping.originalColumn == originalColumn) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + + exports.SourceMapConsumer = SourceMapConsumer; + + /** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The only parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ + function BasicSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && util.isAbsolute(sourceRoot) && util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this.file = file; + } + + BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + + /** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @returns BasicSourceMapConsumer + */ + BasicSourceMapConsumer.fromSourceMap = + function SourceMapConsumer_fromSourceMap(aSourceMap) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = smc._names = ArraySet.fromArray(aSourceMap._names.toArray(), true); + var sources = smc._sources = ArraySet.fromArray(aSourceMap._sources.toArray(), true); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent(smc._sources.toArray(), + smc.sourceRoot); + smc.file = aSourceMap._file; + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = smc.__generatedMappings = []; + var destOriginalMappings = smc.__originalMappings = []; + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping; + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; + }; + + /** + * The version of the source mapping spec that we are consuming. + */ + BasicSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._sources.toArray().map(function (s) { + return this.sourceRoot != null ? util.join(this.sourceRoot, s) : s; + }, this); + } + }); + + /** + * Provide the JIT with a nice shape / hidden class. + */ + function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; + } + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + } + else if (aStr.charAt(index) === ',') { + index++; + } + else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + // Because each offset is encoded relative to the previous one, + // many segments often have the same encoding. We can exploit this + // fact by caching the parsed variable length fields of each segment, + // allowing us to avoid a second parse if we encounter the same + // segment again. + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = cachedSegments[str]; + if (segment) { + index += str.length; + } else { + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + cachedSegments[str] = segment; + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + originalMappings.push(mapping); + } + } + } + + quickSort(generatedMappings, util.compareByGeneratedPositionsDeflated); + this.__generatedMappings = generatedMappings; + + quickSort(originalMappings, util.compareByOriginalPositions); + this.__originalMappings = originalMappings; + }; + + /** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ + BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping(aNeedle, aMappings, aLineName, + aColumnName, aComparator, aBias) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError('Line must be greater than or equal to 1, got ' + + aNeedle[aLineName]); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError('Column must be greater than or equal to 0, got ' + + aNeedle[aColumnName]); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + + /** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ + BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + "generatedLine", + "generatedColumn", + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + if (this.sourceRoot != null) { + source = util.join(this.sourceRoot, source); + } + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null + }; + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { return sc == null; }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + if (this.sourceRoot != null) { + aSource = util.relative(this.sourceRoot, aSource); + } + + if (this._sources.has(aSource)) { + return this.sourcesContent[this._sources.indexOf(aSource)]; + } + + var url; + if (this.sourceRoot != null + && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = aSource.replace(/^file:\/\//, ""); + if (url.scheme == "file" + && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)] + } + + if ((!url.path || url.path == "/") + && this._sources.has("/" + aSource)) { + return this.sourcesContent[this._sources.indexOf("/" + aSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + if (this.sourceRoot != null) { + source = util.relative(this.sourceRoot, source); + } + if (!this._sources.has(source)) { + return { + line: null, + column: null, + lastColumn: null + }; + } + source = this._sources.indexOf(source); + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column') + }; + + var index = this._findMapping( + needle, + this._originalMappings, + "originalLine", + "originalColumn", + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null) + }; + } + } + + return { + line: null, + column: null, + lastColumn: null + }; + }; + + exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + + /** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The only parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ + function IndexedSourceMapConsumer(aSourceMap) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = JSON.parse(aSourceMap.replace(/^\)\]\}'/, '')); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0 + }; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column)) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1 + }, + consumer: new SourceMapConsumer(util.getArg(s, 'map')) + } + }); + } + + IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); + IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + + /** + * The version of the source mapping spec that we are consuming. + */ + IndexedSourceMapConsumer.prototype._version = 3; + + /** + * The list of original sources. + */ + Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + for (var j = 0; j < this._sections[i].consumer.sources.length; j++) { + sources.push(this._sections[i].consumer.sources[j]); + } + } + return sources; + } + }); + + /** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. + * - column: The column number in the generated source. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. + * - column: The column number in the original source, or null. + * - name: The original identifier, or null. + */ + IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column') + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search(needle, this._sections, + function(needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + return (needle.generatedColumn - + section.generatedOffset.generatedColumn); + }); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - + (section.generatedOffset.generatedLine - 1), + column: needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias + }); + }; + + /** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ + IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + + /** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ + IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content) { + return content; + } + } + if (nullOnMissing) { + return null; + } + else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + + /** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. + * - column: The column number in the original source. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. + * - column: The column number in the generated source, or null. + */ + IndexedSourceMapConsumer.prototype.generatedPositionFor = + function IndexedSourceMapConsumer_generatedPositionFor(aArgs) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + // Only consider this section if the requested source is in the list of + // sources of the consumer. + if (section.consumer.sources.indexOf(util.getArg(aArgs, 'source')) === -1) { + continue; + } + var generatedPosition = section.consumer.generatedPositionFor(aArgs); + if (generatedPosition) { + var ret = { + line: generatedPosition.line + + (section.generatedOffset.generatedLine - 1), + column: generatedPosition.column + + (section.generatedOffset.generatedLine === generatedPosition.line + ? section.generatedOffset.generatedColumn - 1 + : 0) + }; + return ret; + } + } + + return { + line: null, + column: null + }; + }; + + /** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (section.consumer.sourceRoot !== null) { + source = util.join(section.consumer.sourceRoot, source); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. + var adjustedMapping = { + source: source, + generatedLine: mapping.generatedLine + + (section.generatedOffset.generatedLine - 1), + generatedColumn: mapping.generatedColumn + + (section.generatedOffset.generatedLine === mapping.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort(this.__generatedMappings, util.compareByGeneratedPositionsDeflated); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + + exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; + + +/***/ }, +/* 8 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + exports.GREATEST_LOWER_BOUND = 1; + exports.LEAST_UPPER_BOUND = 2; + + /** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ + function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } + else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } + else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } + } + + /** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ + exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch(-1, aHaystack.length, aNeedle, aHaystack, + aCompare, aBias || exports.GREATEST_LOWER_BOUND); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; + }; + + +/***/ }, +/* 9 */ +/***/ function(module, exports) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + // It turns out that some (most?) JavaScript engines don't self-host + // `Array.prototype.sort`. This makes sense because C++ will likely remain + // faster than JS when doing raw CPU-intensive sorting. However, when using a + // custom comparator function, calling back and forth between the VM's C++ and + // JIT'd JS is rather slow *and* loses JIT type information, resulting in + // worse generated code for the comparator function than would be optimal. In + // fact, when sorting with a comparator, these costs outweigh the benefits of + // sorting in C++. By using our own JS-implemented Quick Sort (below), we get + // a ~3500ms mean speed-up in `bench/bench.html`. + + /** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ + function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; + } + + /** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ + function randomIntInRange(low, high) { + return Math.round(low + (Math.random() * (high - low))); + } + + /** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ + function doQuickSort(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort(ary, comparator, p, q - 1); + doQuickSort(ary, comparator, q + 1, r); + } + } + + /** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + */ + exports.quickSort = function (ary, comparator) { + doQuickSort(ary, comparator, 0, ary.length - 1); + }; + + +/***/ }, +/* 10 */ +/***/ function(module, exports, __webpack_require__) { + + /* -*- Mode: js; js-indent-level: 2; -*- */ + /* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + + var SourceMapGenerator = __webpack_require__(1).SourceMapGenerator; + var util = __webpack_require__(4); + + // Matches a Windows-style `\r\n` newline or a `\n` newline used by all other + // operating systems these days (capturing the result). + var REGEX_NEWLINE = /(\r?\n)/; + + // Newline character code for charCodeAt() comparisons + var NEWLINE_CODE = 10; + + // Private symbol for identifying `SourceNode`s when multiple versions of + // the source-map library are loaded. This MUST NOT CHANGE across + // versions! + var isSourceNode = "$$$isSourceNode$$$"; + + /** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ + function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); + } + + /** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ + SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap(aGeneratedCode, aSourceMapConsumer, aRelativePath) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are removed from this array, by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var shiftNextLine = function() { + var lineContents = remainingLines.shift(); + // The last line of a file might not have a newline. + var newLine = remainingLines.shift() || ""; + return lineContents + newLine; + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[0]; + var code = nextLine.substr(0, mapping.generatedColumn - + lastGeneratedColumn); + remainingLines[0] = nextLine.substr(mapping.generatedColumn - + lastGeneratedColumn); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[0]; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[0] = nextLine.substr(mapping.generatedColumn); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLines.length > 0) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.join("")); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add(new SourceNode(mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name)); + } + } + }; + + /** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + if (aChunk) { + this.children.push(aChunk); + } + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ + SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length-1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } + else if (aChunk[isSourceNode] || typeof aChunk === "string") { + this.children.unshift(aChunk); + } + else { + throw new TypeError( + "Expected a SourceNode, string, or an array of SourceNodes and strings. Got " + aChunk + ); + } + return this; + }; + + /** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } + else { + if (chunk !== '') { + aFn(chunk, { source: this.source, + line: this.line, + column: this.column, + name: this.name }); + } + } + } + }; + + /** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ + SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len-1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; + }; + + /** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ + SourceNode.prototype.replaceRight = function SourceNode_replaceRight(aPattern, aReplacement) { + var lastChild = this.children[this.children.length - 1]; + if (lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } + else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace(aPattern, aReplacement); + } + else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; + }; + + /** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ + SourceNode.prototype.setSourceContent = + function SourceNode_setSourceContent(aSourceFile, aSourceContent) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; + }; + + /** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ + SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + + /** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ + SourceNode.prototype.toString = function SourceNode_toString() { + var str = ""; + this.walk(function (chunk) { + str += chunk; + }); + return str; + }; + + /** + * Returns the string representation of this source node along with a source + * map. + */ + SourceNode.prototype.toStringWithSourceMap = function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: "", + line: 1, + column: 0 + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if (original.source !== null + && original.line !== null + && original.column !== null) { + if(lastOriginalSource !== original.source + || lastOriginalLine !== original.line + || lastOriginalColumn !== original.column + || lastOriginalName !== original.name) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column + } + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column + }, + generated: { + line: generated.line, + column: generated.column + }, + name: original.name + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + + exports.SourceNode = SourceNode; + + +/***/ } +/******/ ]) +}); +;//Distributed under the BSD license: +//Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> +define('uglifyjs', ['exports', 'source-map', 'logger', 'env!env/file'], function (exports, MOZ_SourceMap, logger, rjsFile) { + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function array_to_hash(a) { + var ret = Object.create(null); + for (var i = 0; i < a.length; ++i) + ret[a[i]] = true; + return ret; +}; + +function slice(a, start) { + return Array.prototype.slice.call(a, start || 0); +}; + +function characters(str) { + return str.split(""); +}; + +function member(name, array) { + return array.indexOf(name) >= 0; +}; + +function find_if(func, array) { + for (var i = 0, n = array.length; i < n; ++i) { + if (func(array[i])) + return array[i]; + } +}; + +function repeat_string(str, i) { + if (i <= 0) return ""; + if (i == 1) return str; + var d = repeat_string(str, i >> 1); + d += d; + if (i & 1) d += str; + return d; +}; + +function configure_error_stack(fn) { + Object.defineProperty(fn.prototype, "stack", { + get: function() { + var err = new Error(this.message); + err.name = this.name; + try { + throw err; + } catch(e) { + return e.stack; + } + } + }); +} + +function DefaultsError(msg, defs) { + this.message = msg; + this.defs = defs; +}; +DefaultsError.prototype = Object.create(Error.prototype); +DefaultsError.prototype.constructor = DefaultsError; +DefaultsError.prototype.name = "DefaultsError"; +configure_error_stack(DefaultsError); + +DefaultsError.croak = function(msg, defs) { + throw new DefaultsError(msg, defs); +}; + +function defaults(args, defs, croak) { + if (args === true) + args = {}; + var ret = args || {}; + if (croak) for (var i in ret) if (HOP(ret, i) && !HOP(defs, i)) + DefaultsError.croak("`" + i + "` is not a supported option", defs); + for (var i in defs) if (HOP(defs, i)) { + ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; + } + return ret; +}; + +function merge(obj, ext) { + var count = 0; + for (var i in ext) if (HOP(ext, i)) { + obj[i] = ext[i]; + count++; + } + return count; +}; + +function noop() {} +function return_false() { return false; } +function return_true() { return true; } +function return_this() { return this; } +function return_null() { return null; } + +var MAP = (function(){ + function MAP(a, f, backwards) { + var ret = [], top = [], i; + function doit() { + var val = f(a[i], i); + var is_last = val instanceof Last; + if (is_last) val = val.v; + if (val instanceof AtTop) { + val = val.v; + if (val instanceof Splice) { + top.push.apply(top, backwards ? val.v.slice().reverse() : val.v); + } else { + top.push(val); + } + } + else if (val !== skip) { + if (val instanceof Splice) { + ret.push.apply(ret, backwards ? val.v.slice().reverse() : val.v); + } else { + ret.push(val); + } + } + return is_last; + }; + if (a instanceof Array) { + if (backwards) { + for (i = a.length; --i >= 0;) if (doit()) break; + ret.reverse(); + top.reverse(); + } else { + for (i = 0; i < a.length; ++i) if (doit()) break; + } + } + else { + for (i in a) if (HOP(a, i)) if (doit()) break; + } + return top.concat(ret); + }; + MAP.at_top = function(val) { return new AtTop(val) }; + MAP.splice = function(val) { return new Splice(val) }; + MAP.last = function(val) { return new Last(val) }; + var skip = MAP.skip = {}; + function AtTop(val) { this.v = val }; + function Splice(val) { this.v = val }; + function Last(val) { this.v = val }; + return MAP; +})(); + +function push_uniq(array, el) { + if (array.indexOf(el) < 0) + array.push(el); +}; + +function string_template(text, props) { + return text.replace(/\{(.+?)\}/g, function(str, p){ + return props && props[p]; + }); +}; + +function remove(array, el) { + for (var i = array.length; --i >= 0;) { + if (array[i] === el) array.splice(i, 1); + } +}; + +function mergeSort(array, cmp) { + if (array.length < 2) return array.slice(); + function merge(a, b) { + var r = [], ai = 0, bi = 0, i = 0; + while (ai < a.length && bi < b.length) { + cmp(a[ai], b[bi]) <= 0 + ? r[i++] = a[ai++] + : r[i++] = b[bi++]; + } + if (ai < a.length) r.push.apply(r, a.slice(ai)); + if (bi < b.length) r.push.apply(r, b.slice(bi)); + return r; + }; + function _ms(a) { + if (a.length <= 1) + return a; + var m = Math.floor(a.length / 2), left = a.slice(0, m), right = a.slice(m); + left = _ms(left); + right = _ms(right); + return merge(left, right); + }; + return _ms(array); +}; + +function set_difference(a, b) { + return a.filter(function(el){ + return b.indexOf(el) < 0; + }); +}; + +function set_intersection(a, b) { + return a.filter(function(el){ + return b.indexOf(el) >= 0; + }); +}; + +// this function is taken from Acorn [1], written by Marijn Haverbeke +// [1] https://github.com/marijnh/acorn +function makePredicate(words) { + if (!(words instanceof Array)) words = words.split(" "); + var f = "", cats = []; + out: for (var i = 0; i < words.length; ++i) { + for (var j = 0; j < cats.length; ++j) + if (cats[j][0].length == words[i].length) { + cats[j].push(words[i]); + continue out; + } + cats.push([words[i]]); + } + function quote(word) { + return JSON.stringify(word).replace(/[\u2028\u2029]/g, function(s) { + switch (s) { + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + } + return s; + }); + } + function compareTo(arr) { + if (arr.length == 1) return f += "return str === " + quote(arr[0]) + ";"; + f += "switch(str){"; + for (var i = 0; i < arr.length; ++i) f += "case " + quote(arr[i]) + ":"; + f += "return true}return false;"; + } + // When there are more than three length categories, an outer + // switch first dispatches on the lengths, to save on comparisons. + if (cats.length > 3) { + cats.sort(function(a, b) {return b.length - a.length;}); + f += "switch(str.length){"; + for (var i = 0; i < cats.length; ++i) { + var cat = cats[i]; + f += "case " + cat[0].length + ":"; + compareTo(cat); + } + f += "}"; + // Otherwise, simply generate a flat `switch` statement. + } else { + compareTo(words); + } + return new Function("str", f); +}; + +function all(array, predicate) { + for (var i = array.length; --i >= 0;) + if (!predicate(array[i])) + return false; + return true; +}; + +function Dictionary() { + this._values = Object.create(null); + this._size = 0; +}; +Dictionary.prototype = { + set: function(key, val) { + if (!this.has(key)) ++this._size; + this._values["$" + key] = val; + return this; + }, + add: function(key, val) { + if (this.has(key)) { + this.get(key).push(val); + } else { + this.set(key, [ val ]); + } + return this; + }, + get: function(key) { return this._values["$" + key] }, + del: function(key) { + if (this.has(key)) { + --this._size; + delete this._values["$" + key]; + } + return this; + }, + has: function(key) { return ("$" + key) in this._values }, + each: function(f) { + for (var i in this._values) + f(this._values[i], i.substr(1)); + }, + size: function() { + return this._size; + }, + map: function(f) { + var ret = []; + for (var i in this._values) + ret.push(f(this._values[i], i.substr(1))); + return ret; + }, + toObject: function() { return this._values } +}; +Dictionary.fromObject = function(obj) { + var dict = new Dictionary(); + dict._size = merge(dict._values, obj); + return dict; +}; + +function HOP(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); +} + +// return true if the node at the top of the stack (that means the +// innermost node in the current output) is lexically the first in +// a statement. +function first_in_statement(stack) { + var node = stack.parent(-1); + for (var i = 0, p; p = stack.parent(i); i++) { + if (p instanceof AST_Statement && p.body === node) + return true; + if ((p instanceof AST_Seq && p.car === node ) || + (p instanceof AST_Call && p.expression === node && !(p instanceof AST_New) ) || + (p instanceof AST_Dot && p.expression === node ) || + (p instanceof AST_Sub && p.expression === node ) || + (p instanceof AST_Conditional && p.condition === node ) || + (p instanceof AST_Binary && p.left === node ) || + (p instanceof AST_UnaryPostfix && p.expression === node )) + { + node = p; + } else { + return false; + } + } +} + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function DEFNODE(type, props, methods, base) { + if (arguments.length < 4) base = AST_Node; + if (!props) props = []; + else props = props.split(/\s+/); + var self_props = props; + if (base && base.PROPS) + props = props.concat(base.PROPS); + var code = "return function AST_" + type + "(props){ if (props) { "; + for (var i = props.length; --i >= 0;) { + code += "this." + props[i] + " = props." + props[i] + ";"; + } + var proto = base && new base; + if (proto && proto.initialize || (methods && methods.initialize)) + code += "this.initialize();"; + code += "}}"; + var ctor = new Function(code)(); + if (proto) { + ctor.prototype = proto; + ctor.BASE = base; + } + if (base) base.SUBCLASSES.push(ctor); + ctor.prototype.CTOR = ctor; + ctor.PROPS = props || null; + ctor.SELF_PROPS = self_props; + ctor.SUBCLASSES = []; + if (type) { + ctor.prototype.TYPE = ctor.TYPE = type; + } + if (methods) for (i in methods) if (HOP(methods, i)) { + if (/^\$/.test(i)) { + ctor[i.substr(1)] = methods[i]; + } else { + ctor.prototype[i] = methods[i]; + } + } + ctor.DEFMETHOD = function(name, method) { + this.prototype[name] = method; + }; + if (typeof exports !== "undefined") { + exports["AST_" + type] = ctor; + } + return ctor; +}; + +var AST_Token = DEFNODE("Token", "type value line col pos endline endcol endpos nlb comments_before file raw", { +}, null); + +var AST_Node = DEFNODE("Node", "start end", { + _clone: function(deep) { + if (deep) { + var self = this.clone(); + return self.transform(new TreeTransformer(function(node) { + if (node !== self) { + return node.clone(true); + } + })); + } + return new this.CTOR(this); + }, + clone: function(deep) { + return this._clone(deep); + }, + $documentation: "Base class of all AST nodes", + $propdoc: { + start: "[AST_Token] The first token of this node", + end: "[AST_Token] The last token of this node" + }, + _walk: function(visitor) { + return visitor._visit(this); + }, + walk: function(visitor) { + return this._walk(visitor); // not sure the indirection will be any help + } +}, null); + +AST_Node.warn_function = null; +AST_Node.warn = function(txt, props) { + if (AST_Node.warn_function) + AST_Node.warn_function(string_template(txt, props)); +}; + +/* -----[ statements ]----- */ + +var AST_Statement = DEFNODE("Statement", null, { + $documentation: "Base class of all statements", +}); + +var AST_Debugger = DEFNODE("Debugger", null, { + $documentation: "Represents a debugger statement", +}, AST_Statement); + +var AST_Directive = DEFNODE("Directive", "value scope quote", { + $documentation: "Represents a directive, like \"use strict\";", + $propdoc: { + value: "[string] The value of this directive as a plain string (it's not an AST_String!)", + scope: "[AST_Scope/S] The scope that this directive affects", + quote: "[string] the original quote character" + }, +}, AST_Statement); + +var AST_SimpleStatement = DEFNODE("SimpleStatement", "body", { + $documentation: "A statement consisting of an expression, i.e. a = 1 + 2", + $propdoc: { + body: "[AST_Node] an expression node (should not be instanceof AST_Statement)" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +function walk_body(node, visitor) { + var body = node.body; + if (body instanceof AST_Statement) { + body._walk(visitor); + } + else for (var i = 0, len = body.length; i < len; i++) { + body[i]._walk(visitor); + } +}; + +var AST_Block = DEFNODE("Block", "body", { + $documentation: "A body of statements (usually bracketed)", + $propdoc: { + body: "[AST_Statement*] an array of statements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + }); + } +}, AST_Statement); + +var AST_BlockStatement = DEFNODE("BlockStatement", null, { + $documentation: "A block statement", +}, AST_Block); + +var AST_EmptyStatement = DEFNODE("EmptyStatement", null, { + $documentation: "The empty statement (empty block or simply a semicolon)", + _walk: function(visitor) { + return visitor._visit(this); + } +}, AST_Statement); + +var AST_StatementWithBody = DEFNODE("StatementWithBody", "body", { + $documentation: "Base class for all statements that contain one nested body: `For`, `ForIn`, `Do`, `While`, `With`", + $propdoc: { + body: "[AST_Statement] the body; this should always be present, even if it's an AST_EmptyStatement" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + }); + } +}, AST_Statement); + +var AST_LabeledStatement = DEFNODE("LabeledStatement", "label", { + $documentation: "Statement with a label", + $propdoc: { + label: "[AST_Label] a label definition" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.label._walk(visitor); + this.body._walk(visitor); + }); + }, + clone: function(deep) { + var node = this._clone(deep); + if (deep) { + var label = node.label; + var def = this.label; + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_LoopControl + && node.label && node.label.thedef === def) { + node.label.thedef = label; + label.references.push(node); + } + })); + } + return node; + } +}, AST_StatementWithBody); + +var AST_IterationStatement = DEFNODE("IterationStatement", null, { + $documentation: "Internal class. All loops inherit from it." +}, AST_StatementWithBody); + +var AST_DWLoop = DEFNODE("DWLoop", "condition", { + $documentation: "Base class for do/while statements", + $propdoc: { + condition: "[AST_Node] the loop condition. Should not be instanceof AST_Statement" + } +}, AST_IterationStatement); + +var AST_Do = DEFNODE("Do", null, { + $documentation: "A `do` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.body._walk(visitor); + this.condition._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_While = DEFNODE("While", null, { + $documentation: "A `while` statement", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_DWLoop); + +var AST_For = DEFNODE("For", "init condition step", { + $documentation: "A `for` statement", + $propdoc: { + init: "[AST_Node?] the `for` initialization code, or null if empty", + condition: "[AST_Node?] the `for` termination clause, or null if empty", + step: "[AST_Node?] the `for` update clause, or null if empty" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.init) this.init._walk(visitor); + if (this.condition) this.condition._walk(visitor); + if (this.step) this.step._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_ForIn = DEFNODE("ForIn", "init name object", { + $documentation: "A `for ... in` statement", + $propdoc: { + init: "[AST_Node] the `for/in` initialization code", + name: "[AST_SymbolRef?] the loop variable, only if `init` is AST_Var", + object: "[AST_Node] the object that we're looping through" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.init._walk(visitor); + this.object._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_IterationStatement); + +var AST_With = DEFNODE("With", "expression", { + $documentation: "A `with` statement", + $propdoc: { + expression: "[AST_Node] the `with` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.body._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ scope and functions ]----- */ + +var AST_Scope = DEFNODE("Scope", "directives variables functions uses_with uses_eval parent_scope enclosed cname", { + $documentation: "Base class for all statements introducing a lexical scope", + $propdoc: { + directives: "[string*/S] an array of directives declared in this scope", + variables: "[Object/S] a map of name -> SymbolDef for all variables/functions defined in this scope", + functions: "[Object/S] like `variables`, but only lists function declarations", + uses_with: "[boolean/S] tells whether this scope uses the `with` statement", + uses_eval: "[boolean/S] tells whether this scope contains a direct call to the global `eval`", + parent_scope: "[AST_Scope?/S] link to the parent scope", + enclosed: "[SymbolDef*/S] a list of all symbol definitions that are accessed from this scope or any subscopes", + cname: "[integer/S] current index for mangling variables (used internally by the mangler)", + }, +}, AST_Block); + +var AST_Toplevel = DEFNODE("Toplevel", "globals", { + $documentation: "The toplevel scope", + $propdoc: { + globals: "[Object/S] a map of name -> SymbolDef for all undeclared names", + }, + wrap_enclose: function(arg_parameter_pairs) { + var self = this; + var args = []; + var parameters = []; + + arg_parameter_pairs.forEach(function(pair) { + var splitAt = pair.lastIndexOf(":"); + + args.push(pair.substr(0, splitAt)); + parameters.push(pair.substr(splitAt + 1)); + }); + + var wrapped_tl = "(function(" + parameters.join(",") + "){ '$ORIG'; })(" + args.join(",") + ")"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive && node.value == "$ORIG") { + return MAP.splice(self.body); + } + })); + return wrapped_tl; + }, + wrap_commonjs: function(name, export_all) { + var self = this; + var to_export = []; + if (export_all) { + self.figure_out_scope(); + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_SymbolDeclaration && node.definition().global) { + if (!find_if(function(n){ return n.name == node.name }, to_export)) + to_export.push(node); + } + })); + } + var wrapped_tl = "(function(exports, global){ '$ORIG'; '$EXPORTS'; global['" + name + "'] = exports; }({}, (function(){return this}())))"; + wrapped_tl = parse(wrapped_tl); + wrapped_tl = wrapped_tl.transform(new TreeTransformer(function before(node){ + if (node instanceof AST_Directive) { + switch (node.value) { + case "$ORIG": + return MAP.splice(self.body); + case "$EXPORTS": + var body = []; + to_export.forEach(function(sym){ + body.push(new AST_SimpleStatement({ + body: new AST_Assign({ + left: new AST_Sub({ + expression: new AST_SymbolRef({ name: "exports" }), + property: new AST_String({ value: sym.name }), + }), + operator: "=", + right: new AST_SymbolRef(sym), + }), + })); + }); + return MAP.splice(body); + } + } + })); + return wrapped_tl; + } +}, AST_Scope); + +var AST_Lambda = DEFNODE("Lambda", "name argnames uses_arguments", { + $documentation: "Base class for functions", + $propdoc: { + name: "[AST_SymbolDeclaration?] the name of this function", + argnames: "[AST_SymbolFunarg*] array of function arguments", + uses_arguments: "[boolean/S] tells whether this function accesses the arguments array" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + if (this.name) this.name._walk(visitor); + var argnames = this.argnames; + for (var i = 0, len = argnames.length; i < len; i++) { + argnames[i]._walk(visitor); + } + walk_body(this, visitor); + }); + } +}, AST_Scope); + +var AST_Accessor = DEFNODE("Accessor", null, { + $documentation: "A setter/getter function. The `name` property is always null." +}, AST_Lambda); + +var AST_Function = DEFNODE("Function", null, { + $documentation: "A function expression" +}, AST_Lambda); + +var AST_Defun = DEFNODE("Defun", null, { + $documentation: "A function definition" +}, AST_Lambda); + +/* -----[ JUMPS ]----- */ + +var AST_Jump = DEFNODE("Jump", null, { + $documentation: "Base class for “jumps†(for now that's `return`, `throw`, `break` and `continue`)" +}, AST_Statement); + +var AST_Exit = DEFNODE("Exit", "value", { + $documentation: "Base class for “exits†(`return` and `throw`)", + $propdoc: { + value: "[AST_Node?] the value returned or thrown by this statement; could be null for AST_Return" + }, + _walk: function(visitor) { + return visitor._visit(this, this.value && function(){ + this.value._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Return = DEFNODE("Return", null, { + $documentation: "A `return` statement" +}, AST_Exit); + +var AST_Throw = DEFNODE("Throw", null, { + $documentation: "A `throw` statement" +}, AST_Exit); + +var AST_LoopControl = DEFNODE("LoopControl", "label", { + $documentation: "Base class for loop control statements (`break` and `continue`)", + $propdoc: { + label: "[AST_LabelRef?] the label, or null if none", + }, + _walk: function(visitor) { + return visitor._visit(this, this.label && function(){ + this.label._walk(visitor); + }); + } +}, AST_Jump); + +var AST_Break = DEFNODE("Break", null, { + $documentation: "A `break` statement" +}, AST_LoopControl); + +var AST_Continue = DEFNODE("Continue", null, { + $documentation: "A `continue` statement" +}, AST_LoopControl); + +/* -----[ IF ]----- */ + +var AST_If = DEFNODE("If", "condition alternative", { + $documentation: "A `if` statement", + $propdoc: { + condition: "[AST_Node] the `if` condition", + alternative: "[AST_Statement?] the `else` part, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.body._walk(visitor); + if (this.alternative) this.alternative._walk(visitor); + }); + } +}, AST_StatementWithBody); + +/* -----[ SWITCH ]----- */ + +var AST_Switch = DEFNODE("Switch", "expression", { + $documentation: "A `switch` statement", + $propdoc: { + expression: "[AST_Node] the `switch` “discriminantâ€" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_SwitchBranch = DEFNODE("SwitchBranch", null, { + $documentation: "Base class for `switch` branches", +}, AST_Block); + +var AST_Default = DEFNODE("Default", null, { + $documentation: "A `default` switch branch", +}, AST_SwitchBranch); + +var AST_Case = DEFNODE("Case", "expression", { + $documentation: "A `case` switch branch", + $propdoc: { + expression: "[AST_Node] the `case` expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_SwitchBranch); + +/* -----[ EXCEPTIONS ]----- */ + +var AST_Try = DEFNODE("Try", "bcatch bfinally", { + $documentation: "A `try` statement", + $propdoc: { + bcatch: "[AST_Catch?] the catch block, or null if not present", + bfinally: "[AST_Finally?] the finally block, or null if not present" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + walk_body(this, visitor); + if (this.bcatch) this.bcatch._walk(visitor); + if (this.bfinally) this.bfinally._walk(visitor); + }); + } +}, AST_Block); + +var AST_Catch = DEFNODE("Catch", "argname", { + $documentation: "A `catch` node; only makes sense as part of a `try` statement", + $propdoc: { + argname: "[AST_SymbolCatch] symbol for the exception" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.argname._walk(visitor); + walk_body(this, visitor); + }); + } +}, AST_Block); + +var AST_Finally = DEFNODE("Finally", null, { + $documentation: "A `finally` node; only makes sense as part of a `try` statement" +}, AST_Block); + +/* -----[ VAR/CONST ]----- */ + +var AST_Definitions = DEFNODE("Definitions", "definitions", { + $documentation: "Base class for `var` or `const` nodes (variable declarations/initializations)", + $propdoc: { + definitions: "[AST_VarDef*] array of variable definitions" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var definitions = this.definitions; + for (var i = 0, len = definitions.length; i < len; i++) { + definitions[i]._walk(visitor); + } + }); + } +}, AST_Statement); + +var AST_Var = DEFNODE("Var", null, { + $documentation: "A `var` statement" +}, AST_Definitions); + +var AST_Const = DEFNODE("Const", null, { + $documentation: "A `const` statement" +}, AST_Definitions); + +var AST_VarDef = DEFNODE("VarDef", "name value", { + $documentation: "A variable declaration; only appears in a AST_Definitions node", + $propdoc: { + name: "[AST_SymbolVar|AST_SymbolConst] name of the variable", + value: "[AST_Node?] initializer, or null of there's no initializer" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.name._walk(visitor); + if (this.value) this.value._walk(visitor); + }); + } +}); + +/* -----[ OTHER ]----- */ + +var AST_Call = DEFNODE("Call", "expression args", { + $documentation: "A function call expression", + $propdoc: { + expression: "[AST_Node] expression to invoke as function", + args: "[AST_Node*] array of arguments" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + var args = this.args; + for (var i = 0, len = args.length; i < len; i++) { + args[i]._walk(visitor); + } + }); + } +}); + +var AST_New = DEFNODE("New", null, { + $documentation: "An object instantiation. Derives from a function call since it has exactly the same properties" +}, AST_Call); + +var AST_Seq = DEFNODE("Seq", "car cdr", { + $documentation: "A sequence expression (two comma-separated expressions)", + $propdoc: { + car: "[AST_Node] first element in sequence", + cdr: "[AST_Node] second element in sequence" + }, + $cons: function(x, y) { + var seq = new AST_Seq(x); + seq.car = x; + seq.cdr = y; + return seq; + }, + $from_array: function(array) { + if (array.length == 0) return null; + if (array.length == 1) return array[0].clone(); + var list = null; + for (var i = array.length; --i >= 0;) { + list = AST_Seq.cons(array[i], list); + } + var p = list; + while (p) { + if (p.cdr && !p.cdr.cdr) { + p.cdr = p.cdr.car; + break; + } + p = p.cdr; + } + return list; + }, + to_array: function() { + var p = this, a = []; + while (p) { + a.push(p.car); + if (p.cdr && !(p.cdr instanceof AST_Seq)) { + a.push(p.cdr); + break; + } + p = p.cdr; + } + return a; + }, + add: function(node) { + var p = this; + while (p) { + if (!(p.cdr instanceof AST_Seq)) { + var cell = AST_Seq.cons(p.cdr, node); + return p.cdr = cell; + } + p = p.cdr; + } + }, + len: function() { + if (this.cdr instanceof AST_Seq) { + return this.cdr.len() + 1; + } else { + return 2; + } + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.car._walk(visitor); + if (this.cdr) this.cdr._walk(visitor); + }); + } +}); + +var AST_PropAccess = DEFNODE("PropAccess", "expression property", { + $documentation: "Base class for property access expressions, i.e. `a.foo` or `a[\"foo\"]`", + $propdoc: { + expression: "[AST_Node] the “container†expression", + property: "[AST_Node|string] the property to access. For AST_Dot this is always a plain string, while for AST_Sub it's an arbitrary AST_Node" + } +}); + +var AST_Dot = DEFNODE("Dot", null, { + $documentation: "A dotted property access expression", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Sub = DEFNODE("Sub", null, { + $documentation: "Index-style property access, i.e. `a[\"foo\"]`", + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + this.property._walk(visitor); + }); + } +}, AST_PropAccess); + +var AST_Unary = DEFNODE("Unary", "operator expression", { + $documentation: "Base class for unary expressions", + $propdoc: { + operator: "[string] the operator", + expression: "[AST_Node] expression that this unary operator applies to" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.expression._walk(visitor); + }); + } +}); + +var AST_UnaryPrefix = DEFNODE("UnaryPrefix", null, { + $documentation: "Unary prefix expression, i.e. `typeof i` or `++i`" +}, AST_Unary); + +var AST_UnaryPostfix = DEFNODE("UnaryPostfix", null, { + $documentation: "Unary postfix expression, i.e. `i++`" +}, AST_Unary); + +var AST_Binary = DEFNODE("Binary", "left operator right", { + $documentation: "Binary expression, i.e. `a + b`", + $propdoc: { + left: "[AST_Node] left-hand side expression", + operator: "[string] the operator", + right: "[AST_Node] right-hand side expression" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.left._walk(visitor); + this.right._walk(visitor); + }); + } +}); + +var AST_Conditional = DEFNODE("Conditional", "condition consequent alternative", { + $documentation: "Conditional expression using the ternary operator, i.e. `a ? b : c`", + $propdoc: { + condition: "[AST_Node]", + consequent: "[AST_Node]", + alternative: "[AST_Node]" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.condition._walk(visitor); + this.consequent._walk(visitor); + this.alternative._walk(visitor); + }); + } +}); + +var AST_Assign = DEFNODE("Assign", null, { + $documentation: "An assignment expression — `a = b + 5`", +}, AST_Binary); + +/* -----[ LITERALS ]----- */ + +var AST_Array = DEFNODE("Array", "elements", { + $documentation: "An array literal", + $propdoc: { + elements: "[AST_Node*] array of elements" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var elements = this.elements; + for (var i = 0, len = elements.length; i < len; i++) { + elements[i]._walk(visitor); + } + }); + } +}); + +var AST_Object = DEFNODE("Object", "properties", { + $documentation: "An object literal", + $propdoc: { + properties: "[AST_ObjectProperty*] array of properties" + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + var properties = this.properties; + for (var i = 0, len = properties.length; i < len; i++) { + properties[i]._walk(visitor); + } + }); + } +}); + +var AST_ObjectProperty = DEFNODE("ObjectProperty", "key value", { + $documentation: "Base class for literal object properties", + $propdoc: { + key: "[string] the property name converted to a string for ObjectKeyVal. For setters and getters this is an AST_SymbolAccessor.", + value: "[AST_Node] property value. For setters and getters this is an AST_Accessor." + }, + _walk: function(visitor) { + return visitor._visit(this, function(){ + this.value._walk(visitor); + }); + } +}); + +var AST_ObjectKeyVal = DEFNODE("ObjectKeyVal", "quote", { + $documentation: "A key: value object property", + $propdoc: { + quote: "[string] the original quote character" + } +}, AST_ObjectProperty); + +var AST_ObjectSetter = DEFNODE("ObjectSetter", null, { + $documentation: "An object setter property", +}, AST_ObjectProperty); + +var AST_ObjectGetter = DEFNODE("ObjectGetter", null, { + $documentation: "An object getter property", +}, AST_ObjectProperty); + +var AST_Symbol = DEFNODE("Symbol", "scope name thedef", { + $propdoc: { + name: "[string] name of this symbol", + scope: "[AST_Scope/S] the current scope (not necessarily the definition scope)", + thedef: "[SymbolDef/S] the definition of this symbol" + }, + $documentation: "Base class for all symbols", +}); + +var AST_SymbolAccessor = DEFNODE("SymbolAccessor", null, { + $documentation: "The name of a property accessor (setter/getter function)" +}, AST_Symbol); + +var AST_SymbolDeclaration = DEFNODE("SymbolDeclaration", "init", { + $documentation: "A declaration symbol (symbol in var/const, function name or argument, symbol in catch)", +}, AST_Symbol); + +var AST_SymbolVar = DEFNODE("SymbolVar", null, { + $documentation: "Symbol defining a variable", +}, AST_SymbolDeclaration); + +var AST_SymbolConst = DEFNODE("SymbolConst", null, { + $documentation: "A constant declaration" +}, AST_SymbolDeclaration); + +var AST_SymbolFunarg = DEFNODE("SymbolFunarg", null, { + $documentation: "Symbol naming a function argument", +}, AST_SymbolVar); + +var AST_SymbolDefun = DEFNODE("SymbolDefun", null, { + $documentation: "Symbol defining a function", +}, AST_SymbolDeclaration); + +var AST_SymbolLambda = DEFNODE("SymbolLambda", null, { + $documentation: "Symbol naming a function expression", +}, AST_SymbolDeclaration); + +var AST_SymbolCatch = DEFNODE("SymbolCatch", null, { + $documentation: "Symbol naming the exception in catch", +}, AST_SymbolDeclaration); + +var AST_Label = DEFNODE("Label", "references", { + $documentation: "Symbol naming a label (declaration)", + $propdoc: { + references: "[AST_LoopControl*] a list of nodes referring to this label" + }, + initialize: function() { + this.references = []; + this.thedef = this; + } +}, AST_Symbol); + +var AST_SymbolRef = DEFNODE("SymbolRef", null, { + $documentation: "Reference to some symbol (not definition/declaration)", +}, AST_Symbol); + +var AST_LabelRef = DEFNODE("LabelRef", null, { + $documentation: "Reference to a label symbol", +}, AST_Symbol); + +var AST_This = DEFNODE("This", null, { + $documentation: "The `this` symbol", +}, AST_Symbol); + +var AST_Constant = DEFNODE("Constant", null, { + $documentation: "Base class for all constants", + getValue: function() { + return this.value; + } +}); + +var AST_String = DEFNODE("String", "value quote", { + $documentation: "A string literal", + $propdoc: { + value: "[string] the contents of this string", + quote: "[string] the original quote character" + } +}, AST_Constant); + +var AST_Number = DEFNODE("Number", "value literal", { + $documentation: "A number literal", + $propdoc: { + value: "[number] the numeric value", + literal: "[string] numeric value as string (optional)" + } +}, AST_Constant); + +var AST_RegExp = DEFNODE("RegExp", "value", { + $documentation: "A regexp literal", + $propdoc: { + value: "[RegExp] the actual regexp" + } +}, AST_Constant); + +var AST_Atom = DEFNODE("Atom", null, { + $documentation: "Base class for atoms", +}, AST_Constant); + +var AST_Null = DEFNODE("Null", null, { + $documentation: "The `null` atom", + value: null +}, AST_Atom); + +var AST_NaN = DEFNODE("NaN", null, { + $documentation: "The impossible value", + value: 0/0 +}, AST_Atom); + +var AST_Undefined = DEFNODE("Undefined", null, { + $documentation: "The `undefined` value", + value: (function(){}()) +}, AST_Atom); + +var AST_Hole = DEFNODE("Hole", null, { + $documentation: "A hole in an array", + value: (function(){}()) +}, AST_Atom); + +var AST_Infinity = DEFNODE("Infinity", null, { + $documentation: "The `Infinity` value", + value: 1/0 +}, AST_Atom); + +var AST_Boolean = DEFNODE("Boolean", null, { + $documentation: "Base class for booleans", +}, AST_Atom); + +var AST_False = DEFNODE("False", null, { + $documentation: "The `false` atom", + value: false +}, AST_Boolean); + +var AST_True = DEFNODE("True", null, { + $documentation: "The `true` atom", + value: true +}, AST_Boolean); + +/* -----[ TreeWalker ]----- */ + +function TreeWalker(callback) { + this.visit = callback; + this.stack = []; + this.directives = Object.create(null); +}; +TreeWalker.prototype = { + _visit: function(node, descend) { + this.push(node); + var ret = this.visit(node, descend ? function(){ + descend.call(node); + } : noop); + if (!ret && descend) { + descend.call(node); + } + this.pop(node); + return ret; + }, + parent: function(n) { + return this.stack[this.stack.length - 2 - (n || 0)]; + }, + push: function (node) { + if (node instanceof AST_Lambda) { + this.directives = Object.create(this.directives); + } else if (node instanceof AST_Directive && !this.directives[node.value]) { + this.directives[node.value] = node; + } + this.stack.push(node); + }, + pop: function(node) { + this.stack.pop(); + if (node instanceof AST_Lambda) { + this.directives = Object.getPrototypeOf(this.directives); + } + }, + self: function() { + return this.stack[this.stack.length - 1]; + }, + find_parent: function(type) { + var stack = this.stack; + for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof type) return x; + } + }, + has_directive: function(type) { + var dir = this.directives[type]; + if (dir) return dir; + var node = this.stack[this.stack.length - 1]; + if (node instanceof AST_Scope) { + for (var i = 0; i < node.body.length; ++i) { + var st = node.body[i]; + if (!(st instanceof AST_Directive)) break; + if (st.value == type) return st; + } + } + }, + in_boolean_context: function() { + var stack = this.stack; + var i = stack.length, self = stack[--i]; + while (i > 0) { + var p = stack[--i]; + if ((p instanceof AST_If && p.condition === self) || + (p instanceof AST_Conditional && p.condition === self) || + (p instanceof AST_DWLoop && p.condition === self) || + (p instanceof AST_For && p.condition === self) || + (p instanceof AST_UnaryPrefix && p.operator == "!" && p.expression === self)) + { + return true; + } + if (!(p instanceof AST_Binary && (p.operator == "&&" || p.operator == "||"))) + return false; + self = p; + } + }, + loopcontrol_target: function(node) { + var stack = this.stack; + if (node.label) for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_LabeledStatement && x.label.name == node.label.name) + return x.body; + } else for (var i = stack.length; --i >= 0;) { + var x = stack[i]; + if (x instanceof AST_IterationStatement + || node instanceof AST_Break && x instanceof AST_Switch) + return x; + } + } +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + Parser based on parse-js (http://marijn.haverbeke.nl/parse-js/). + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var KEYWORDS = 'break case catch const continue debugger default delete do else finally for function if in instanceof new return switch throw try typeof var void while with'; +var KEYWORDS_ATOM = 'false null true'; +var RESERVED_WORDS = 'abstract boolean byte char class double enum export extends final float goto implements import int interface let long native package private protected public short static super synchronized this throws transient volatile yield' + + " " + KEYWORDS_ATOM + " " + KEYWORDS; +var KEYWORDS_BEFORE_EXPRESSION = 'return new delete throw else case'; + +KEYWORDS = makePredicate(KEYWORDS); +RESERVED_WORDS = makePredicate(RESERVED_WORDS); +KEYWORDS_BEFORE_EXPRESSION = makePredicate(KEYWORDS_BEFORE_EXPRESSION); +KEYWORDS_ATOM = makePredicate(KEYWORDS_ATOM); + +var OPERATOR_CHARS = makePredicate(characters("+-*&%=<>!?|~^")); + +var RE_HEX_NUMBER = /^0x[0-9a-f]+$/i; +var RE_OCT_NUMBER = /^0[0-7]+$/; + +var OPERATORS = makePredicate([ + "in", + "instanceof", + "typeof", + "new", + "void", + "delete", + "++", + "--", + "+", + "-", + "!", + "~", + "&", + "|", + "^", + "*", + "/", + "%", + ">>", + "<<", + ">>>", + "<", + ">", + "<=", + ">=", + "==", + "===", + "!=", + "!==", + "?", + "=", + "+=", + "-=", + "/=", + "*=", + "%=", + ">>=", + "<<=", + ">>>=", + "|=", + "^=", + "&=", + "&&", + "||" +]); + +var WHITESPACE_CHARS = makePredicate(characters(" \u00a0\n\r\t\f\u000b\u200b\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u2028\u2029\u202f\u205f\u3000\uFEFF")); + +var NEWLINE_CHARS = makePredicate(characters("\n\r\u2028\u2029")); + +var PUNC_BEFORE_EXPRESSION = makePredicate(characters("[{(,;:")); + +var PUNC_CHARS = makePredicate(characters("[]{}(),;:")); + +var REGEXP_MODIFIERS = makePredicate(characters("gmsiy")); + +/* -----[ Tokenizer ]----- */ + +// regexps adapted from http://xregexp.com/plugins/#unicode +var UNICODE = { + letter: new RegExp("[\\u0041-\\u005A\\u0061-\\u007A\\u00AA\\u00B5\\u00BA\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02C1\\u02C6-\\u02D1\\u02E0-\\u02E4\\u02EC\\u02EE\\u0370-\\u0374\\u0376\\u0377\\u037A-\\u037D\\u037F\\u0386\\u0388-\\u038A\\u038C\\u038E-\\u03A1\\u03A3-\\u03F5\\u03F7-\\u0481\\u048A-\\u052F\\u0531-\\u0556\\u0559\\u0561-\\u0587\\u05D0-\\u05EA\\u05F0-\\u05F2\\u0620-\\u064A\\u066E\\u066F\\u0671-\\u06D3\\u06D5\\u06E5\\u06E6\\u06EE\\u06EF\\u06FA-\\u06FC\\u06FF\\u0710\\u0712-\\u072F\\u074D-\\u07A5\\u07B1\\u07CA-\\u07EA\\u07F4\\u07F5\\u07FA\\u0800-\\u0815\\u081A\\u0824\\u0828\\u0840-\\u0858\\u08A0-\\u08B2\\u0904-\\u0939\\u093D\\u0950\\u0958-\\u0961\\u0971-\\u0980\\u0985-\\u098C\\u098F\\u0990\\u0993-\\u09A8\\u09AA-\\u09B0\\u09B2\\u09B6-\\u09B9\\u09BD\\u09CE\\u09DC\\u09DD\\u09DF-\\u09E1\\u09F0\\u09F1\\u0A05-\\u0A0A\\u0A0F\\u0A10\\u0A13-\\u0A28\\u0A2A-\\u0A30\\u0A32\\u0A33\\u0A35\\u0A36\\u0A38\\u0A39\\u0A59-\\u0A5C\\u0A5E\\u0A72-\\u0A74\\u0A85-\\u0A8D\\u0A8F-\\u0A91\\u0A93-\\u0AA8\\u0AAA-\\u0AB0\\u0AB2\\u0AB3\\u0AB5-\\u0AB9\\u0ABD\\u0AD0\\u0AE0\\u0AE1\\u0B05-\\u0B0C\\u0B0F\\u0B10\\u0B13-\\u0B28\\u0B2A-\\u0B30\\u0B32\\u0B33\\u0B35-\\u0B39\\u0B3D\\u0B5C\\u0B5D\\u0B5F-\\u0B61\\u0B71\\u0B83\\u0B85-\\u0B8A\\u0B8E-\\u0B90\\u0B92-\\u0B95\\u0B99\\u0B9A\\u0B9C\\u0B9E\\u0B9F\\u0BA3\\u0BA4\\u0BA8-\\u0BAA\\u0BAE-\\u0BB9\\u0BD0\\u0C05-\\u0C0C\\u0C0E-\\u0C10\\u0C12-\\u0C28\\u0C2A-\\u0C39\\u0C3D\\u0C58\\u0C59\\u0C60\\u0C61\\u0C85-\\u0C8C\\u0C8E-\\u0C90\\u0C92-\\u0CA8\\u0CAA-\\u0CB3\\u0CB5-\\u0CB9\\u0CBD\\u0CDE\\u0CE0\\u0CE1\\u0CF1\\u0CF2\\u0D05-\\u0D0C\\u0D0E-\\u0D10\\u0D12-\\u0D3A\\u0D3D\\u0D4E\\u0D60\\u0D61\\u0D7A-\\u0D7F\\u0D85-\\u0D96\\u0D9A-\\u0DB1\\u0DB3-\\u0DBB\\u0DBD\\u0DC0-\\u0DC6\\u0E01-\\u0E30\\u0E32\\u0E33\\u0E40-\\u0E46\\u0E81\\u0E82\\u0E84\\u0E87\\u0E88\\u0E8A\\u0E8D\\u0E94-\\u0E97\\u0E99-\\u0E9F\\u0EA1-\\u0EA3\\u0EA5\\u0EA7\\u0EAA\\u0EAB\\u0EAD-\\u0EB0\\u0EB2\\u0EB3\\u0EBD\\u0EC0-\\u0EC4\\u0EC6\\u0EDC-\\u0EDF\\u0F00\\u0F40-\\u0F47\\u0F49-\\u0F6C\\u0F88-\\u0F8C\\u1000-\\u102A\\u103F\\u1050-\\u1055\\u105A-\\u105D\\u1061\\u1065\\u1066\\u106E-\\u1070\\u1075-\\u1081\\u108E\\u10A0-\\u10C5\\u10C7\\u10CD\\u10D0-\\u10FA\\u10FC-\\u1248\\u124A-\\u124D\\u1250-\\u1256\\u1258\\u125A-\\u125D\\u1260-\\u1288\\u128A-\\u128D\\u1290-\\u12B0\\u12B2-\\u12B5\\u12B8-\\u12BE\\u12C0\\u12C2-\\u12C5\\u12C8-\\u12D6\\u12D8-\\u1310\\u1312-\\u1315\\u1318-\\u135A\\u1380-\\u138F\\u13A0-\\u13F4\\u1401-\\u166C\\u166F-\\u167F\\u1681-\\u169A\\u16A0-\\u16EA\\u16EE-\\u16F8\\u1700-\\u170C\\u170E-\\u1711\\u1720-\\u1731\\u1740-\\u1751\\u1760-\\u176C\\u176E-\\u1770\\u1780-\\u17B3\\u17D7\\u17DC\\u1820-\\u1877\\u1880-\\u18A8\\u18AA\\u18B0-\\u18F5\\u1900-\\u191E\\u1950-\\u196D\\u1970-\\u1974\\u1980-\\u19AB\\u19C1-\\u19C7\\u1A00-\\u1A16\\u1A20-\\u1A54\\u1AA7\\u1B05-\\u1B33\\u1B45-\\u1B4B\\u1B83-\\u1BA0\\u1BAE\\u1BAF\\u1BBA-\\u1BE5\\u1C00-\\u1C23\\u1C4D-\\u1C4F\\u1C5A-\\u1C7D\\u1CE9-\\u1CEC\\u1CEE-\\u1CF1\\u1CF5\\u1CF6\\u1D00-\\u1DBF\\u1E00-\\u1F15\\u1F18-\\u1F1D\\u1F20-\\u1F45\\u1F48-\\u1F4D\\u1F50-\\u1F57\\u1F59\\u1F5B\\u1F5D\\u1F5F-\\u1F7D\\u1F80-\\u1FB4\\u1FB6-\\u1FBC\\u1FBE\\u1FC2-\\u1FC4\\u1FC6-\\u1FCC\\u1FD0-\\u1FD3\\u1FD6-\\u1FDB\\u1FE0-\\u1FEC\\u1FF2-\\u1FF4\\u1FF6-\\u1FFC\\u2071\\u207F\\u2090-\\u209C\\u2102\\u2107\\u210A-\\u2113\\u2115\\u2119-\\u211D\\u2124\\u2126\\u2128\\u212A-\\u212D\\u212F-\\u2139\\u213C-\\u213F\\u2145-\\u2149\\u214E\\u2160-\\u2188\\u2C00-\\u2C2E\\u2C30-\\u2C5E\\u2C60-\\u2CE4\\u2CEB-\\u2CEE\\u2CF2\\u2CF3\\u2D00-\\u2D25\\u2D27\\u2D2D\\u2D30-\\u2D67\\u2D6F\\u2D80-\\u2D96\\u2DA0-\\u2DA6\\u2DA8-\\u2DAE\\u2DB0-\\u2DB6\\u2DB8-\\u2DBE\\u2DC0-\\u2DC6\\u2DC8-\\u2DCE\\u2DD0-\\u2DD6\\u2DD8-\\u2DDE\\u2E2F\\u3005-\\u3007\\u3021-\\u3029\\u3031-\\u3035\\u3038-\\u303C\\u3041-\\u3096\\u309D-\\u309F\\u30A1-\\u30FA\\u30FC-\\u30FF\\u3105-\\u312D\\u3131-\\u318E\\u31A0-\\u31BA\\u31F0-\\u31FF\\u3400-\\u4DB5\\u4E00-\\u9FCC\\uA000-\\uA48C\\uA4D0-\\uA4FD\\uA500-\\uA60C\\uA610-\\uA61F\\uA62A\\uA62B\\uA640-\\uA66E\\uA67F-\\uA69D\\uA6A0-\\uA6EF\\uA717-\\uA71F\\uA722-\\uA788\\uA78B-\\uA78E\\uA790-\\uA7AD\\uA7B0\\uA7B1\\uA7F7-\\uA801\\uA803-\\uA805\\uA807-\\uA80A\\uA80C-\\uA822\\uA840-\\uA873\\uA882-\\uA8B3\\uA8F2-\\uA8F7\\uA8FB\\uA90A-\\uA925\\uA930-\\uA946\\uA960-\\uA97C\\uA984-\\uA9B2\\uA9CF\\uA9E0-\\uA9E4\\uA9E6-\\uA9EF\\uA9FA-\\uA9FE\\uAA00-\\uAA28\\uAA40-\\uAA42\\uAA44-\\uAA4B\\uAA60-\\uAA76\\uAA7A\\uAA7E-\\uAAAF\\uAAB1\\uAAB5\\uAAB6\\uAAB9-\\uAABD\\uAAC0\\uAAC2\\uAADB-\\uAADD\\uAAE0-\\uAAEA\\uAAF2-\\uAAF4\\uAB01-\\uAB06\\uAB09-\\uAB0E\\uAB11-\\uAB16\\uAB20-\\uAB26\\uAB28-\\uAB2E\\uAB30-\\uAB5A\\uAB5C-\\uAB5F\\uAB64\\uAB65\\uABC0-\\uABE2\\uAC00-\\uD7A3\\uD7B0-\\uD7C6\\uD7CB-\\uD7FB\\uF900-\\uFA6D\\uFA70-\\uFAD9\\uFB00-\\uFB06\\uFB13-\\uFB17\\uFB1D\\uFB1F-\\uFB28\\uFB2A-\\uFB36\\uFB38-\\uFB3C\\uFB3E\\uFB40\\uFB41\\uFB43\\uFB44\\uFB46-\\uFBB1\\uFBD3-\\uFD3D\\uFD50-\\uFD8F\\uFD92-\\uFDC7\\uFDF0-\\uFDFB\\uFE70-\\uFE74\\uFE76-\\uFEFC\\uFF21-\\uFF3A\\uFF41-\\uFF5A\\uFF66-\\uFFBE\\uFFC2-\\uFFC7\\uFFCA-\\uFFCF\\uFFD2-\\uFFD7\\uFFDA-\\uFFDC]"), + digit: new RegExp("[\\u0030-\\u0039\\u0660-\\u0669\\u06F0-\\u06F9\\u07C0-\\u07C9\\u0966-\\u096F\\u09E6-\\u09EF\\u0A66-\\u0A6F\\u0AE6-\\u0AEF\\u0B66-\\u0B6F\\u0BE6-\\u0BEF\\u0C66-\\u0C6F\\u0CE6-\\u0CEF\\u0D66-\\u0D6F\\u0DE6-\\u0DEF\\u0E50-\\u0E59\\u0ED0-\\u0ED9\\u0F20-\\u0F29\\u1040-\\u1049\\u1090-\\u1099\\u17E0-\\u17E9\\u1810-\\u1819\\u1946-\\u194F\\u19D0-\\u19D9\\u1A80-\\u1A89\\u1A90-\\u1A99\\u1B50-\\u1B59\\u1BB0-\\u1BB9\\u1C40-\\u1C49\\u1C50-\\u1C59\\uA620-\\uA629\\uA8D0-\\uA8D9\\uA900-\\uA909\\uA9D0-\\uA9D9\\uA9F0-\\uA9F9\\uAA50-\\uAA59\\uABF0-\\uABF9\\uFF10-\\uFF19]"), + non_spacing_mark: new RegExp("[\\u0300-\\u036F\\u0483-\\u0487\\u0591-\\u05BD\\u05BF\\u05C1\\u05C2\\u05C4\\u05C5\\u05C7\\u0610-\\u061A\\u064B-\\u065E\\u0670\\u06D6-\\u06DC\\u06DF-\\u06E4\\u06E7\\u06E8\\u06EA-\\u06ED\\u0711\\u0730-\\u074A\\u07A6-\\u07B0\\u07EB-\\u07F3\\u0816-\\u0819\\u081B-\\u0823\\u0825-\\u0827\\u0829-\\u082D\\u0900-\\u0902\\u093C\\u0941-\\u0948\\u094D\\u0951-\\u0955\\u0962\\u0963\\u0981\\u09BC\\u09C1-\\u09C4\\u09CD\\u09E2\\u09E3\\u0A01\\u0A02\\u0A3C\\u0A41\\u0A42\\u0A47\\u0A48\\u0A4B-\\u0A4D\\u0A51\\u0A70\\u0A71\\u0A75\\u0A81\\u0A82\\u0ABC\\u0AC1-\\u0AC5\\u0AC7\\u0AC8\\u0ACD\\u0AE2\\u0AE3\\u0B01\\u0B3C\\u0B3F\\u0B41-\\u0B44\\u0B4D\\u0B56\\u0B62\\u0B63\\u0B82\\u0BC0\\u0BCD\\u0C3E-\\u0C40\\u0C46-\\u0C48\\u0C4A-\\u0C4D\\u0C55\\u0C56\\u0C62\\u0C63\\u0CBC\\u0CBF\\u0CC6\\u0CCC\\u0CCD\\u0CE2\\u0CE3\\u0D41-\\u0D44\\u0D4D\\u0D62\\u0D63\\u0DCA\\u0DD2-\\u0DD4\\u0DD6\\u0E31\\u0E34-\\u0E3A\\u0E47-\\u0E4E\\u0EB1\\u0EB4-\\u0EB9\\u0EBB\\u0EBC\\u0EC8-\\u0ECD\\u0F18\\u0F19\\u0F35\\u0F37\\u0F39\\u0F71-\\u0F7E\\u0F80-\\u0F84\\u0F86\\u0F87\\u0F90-\\u0F97\\u0F99-\\u0FBC\\u0FC6\\u102D-\\u1030\\u1032-\\u1037\\u1039\\u103A\\u103D\\u103E\\u1058\\u1059\\u105E-\\u1060\\u1071-\\u1074\\u1082\\u1085\\u1086\\u108D\\u109D\\u135F\\u1712-\\u1714\\u1732-\\u1734\\u1752\\u1753\\u1772\\u1773\\u17B7-\\u17BD\\u17C6\\u17C9-\\u17D3\\u17DD\\u180B-\\u180D\\u18A9\\u1920-\\u1922\\u1927\\u1928\\u1932\\u1939-\\u193B\\u1A17\\u1A18\\u1A56\\u1A58-\\u1A5E\\u1A60\\u1A62\\u1A65-\\u1A6C\\u1A73-\\u1A7C\\u1A7F\\u1B00-\\u1B03\\u1B34\\u1B36-\\u1B3A\\u1B3C\\u1B42\\u1B6B-\\u1B73\\u1B80\\u1B81\\u1BA2-\\u1BA5\\u1BA8\\u1BA9\\u1C2C-\\u1C33\\u1C36\\u1C37\\u1CD0-\\u1CD2\\u1CD4-\\u1CE0\\u1CE2-\\u1CE8\\u1CED\\u1DC0-\\u1DE6\\u1DFD-\\u1DFF\\u20D0-\\u20DC\\u20E1\\u20E5-\\u20F0\\u2CEF-\\u2CF1\\u2DE0-\\u2DFF\\u302A-\\u302F\\u3099\\u309A\\uA66F\\uA67C\\uA67D\\uA6F0\\uA6F1\\uA802\\uA806\\uA80B\\uA825\\uA826\\uA8C4\\uA8E0-\\uA8F1\\uA926-\\uA92D\\uA947-\\uA951\\uA980-\\uA982\\uA9B3\\uA9B6-\\uA9B9\\uA9BC\\uAA29-\\uAA2E\\uAA31\\uAA32\\uAA35\\uAA36\\uAA43\\uAA4C\\uAAB0\\uAAB2-\\uAAB4\\uAAB7\\uAAB8\\uAABE\\uAABF\\uAAC1\\uABE5\\uABE8\\uABED\\uFB1E\\uFE00-\\uFE0F\\uFE20-\\uFE26]"), + space_combining_mark: new RegExp("[\\u0903\\u093E-\\u0940\\u0949-\\u094C\\u094E\\u0982\\u0983\\u09BE-\\u09C0\\u09C7\\u09C8\\u09CB\\u09CC\\u09D7\\u0A03\\u0A3E-\\u0A40\\u0A83\\u0ABE-\\u0AC0\\u0AC9\\u0ACB\\u0ACC\\u0B02\\u0B03\\u0B3E\\u0B40\\u0B47\\u0B48\\u0B4B\\u0B4C\\u0B57\\u0BBE\\u0BBF\\u0BC1\\u0BC2\\u0BC6-\\u0BC8\\u0BCA-\\u0BCC\\u0BD7\\u0C01-\\u0C03\\u0C41-\\u0C44\\u0C82\\u0C83\\u0CBE\\u0CC0-\\u0CC4\\u0CC7\\u0CC8\\u0CCA\\u0CCB\\u0CD5\\u0CD6\\u0D02\\u0D03\\u0D3E-\\u0D40\\u0D46-\\u0D48\\u0D4A-\\u0D4C\\u0D57\\u0D82\\u0D83\\u0DCF-\\u0DD1\\u0DD8-\\u0DDF\\u0DF2\\u0DF3\\u0F3E\\u0F3F\\u0F7F\\u102B\\u102C\\u1031\\u1038\\u103B\\u103C\\u1056\\u1057\\u1062-\\u1064\\u1067-\\u106D\\u1083\\u1084\\u1087-\\u108C\\u108F\\u109A-\\u109C\\u17B6\\u17BE-\\u17C5\\u17C7\\u17C8\\u1923-\\u1926\\u1929-\\u192B\\u1930\\u1931\\u1933-\\u1938\\u19B0-\\u19C0\\u19C8\\u19C9\\u1A19-\\u1A1B\\u1A55\\u1A57\\u1A61\\u1A63\\u1A64\\u1A6D-\\u1A72\\u1B04\\u1B35\\u1B3B\\u1B3D-\\u1B41\\u1B43\\u1B44\\u1B82\\u1BA1\\u1BA6\\u1BA7\\u1BAA\\u1C24-\\u1C2B\\u1C34\\u1C35\\u1CE1\\u1CF2\\uA823\\uA824\\uA827\\uA880\\uA881\\uA8B4-\\uA8C3\\uA952\\uA953\\uA983\\uA9B4\\uA9B5\\uA9BA\\uA9BB\\uA9BD-\\uA9C0\\uAA2F\\uAA30\\uAA33\\uAA34\\uAA4D\\uAA7B\\uABE3\\uABE4\\uABE6\\uABE7\\uABE9\\uABEA\\uABEC]"), + connector_punctuation: new RegExp("[\\u005F\\u203F\\u2040\\u2054\\uFE33\\uFE34\\uFE4D-\\uFE4F\\uFF3F]") +}; + +function is_letter(code) { + return (code >= 97 && code <= 122) + || (code >= 65 && code <= 90) + || (code >= 0xaa && UNICODE.letter.test(String.fromCharCode(code))); +}; + +function is_digit(code) { + return code >= 48 && code <= 57; +}; + +function is_alphanumeric_char(code) { + return is_digit(code) || is_letter(code); +}; + +function is_unicode_digit(code) { + return UNICODE.digit.test(String.fromCharCode(code)); +} + +function is_unicode_combining_mark(ch) { + return UNICODE.non_spacing_mark.test(ch) || UNICODE.space_combining_mark.test(ch); +}; + +function is_unicode_connector_punctuation(ch) { + return UNICODE.connector_punctuation.test(ch); +}; + +function is_identifier(name) { + return !RESERVED_WORDS(name) && /^[a-z_$][a-z0-9_$]*$/i.test(name); +}; + +function is_identifier_start(code) { + return code == 36 || code == 95 || is_letter(code); +}; + +function is_identifier_char(ch) { + var code = ch.charCodeAt(0); + return is_identifier_start(code) + || is_digit(code) + || code == 8204 // \u200c: zero-width non-joiner <ZWNJ> + || code == 8205 // \u200d: zero-width joiner <ZWJ> (in my ECMA-262 PDF, this is also 200c) + || is_unicode_combining_mark(ch) + || is_unicode_connector_punctuation(ch) + || is_unicode_digit(code) + ; +}; + +function is_identifier_string(str){ + return /^[a-z_$][a-z0-9_$]*$/i.test(str); +}; + +function parse_js_number(num) { + if (RE_HEX_NUMBER.test(num)) { + return parseInt(num.substr(2), 16); + } else if (RE_OCT_NUMBER.test(num)) { + return parseInt(num.substr(1), 8); + } else { + var val = parseFloat(num); + if (val == num) return val; + } +}; + +function JS_Parse_Error(message, filename, line, col, pos) { + this.message = message; + this.filename = filename; + this.line = line; + this.col = col; + this.pos = pos; +}; +JS_Parse_Error.prototype = Object.create(Error.prototype); +JS_Parse_Error.prototype.constructor = JS_Parse_Error; +JS_Parse_Error.prototype.name = "SyntaxError"; +configure_error_stack(JS_Parse_Error); + +function js_error(message, filename, line, col, pos) { + throw new JS_Parse_Error(message, filename, line, col, pos); +}; + +function is_token(token, type, val) { + return token.type == type && (val == null || token.value == val); +}; + +var EX_EOF = {}; + +function tokenizer($TEXT, filename, html5_comments, shebang) { + + var S = { + text : $TEXT, + filename : filename, + pos : 0, + tokpos : 0, + line : 1, + tokline : 0, + col : 0, + tokcol : 0, + newline_before : false, + regex_allowed : false, + comments_before : [], + directives : {}, + directive_stack : [] + }; + + function peek() { return S.text.charAt(S.pos); }; + + function next(signal_eof, in_string) { + var ch = S.text.charAt(S.pos++); + if (signal_eof && !ch) + throw EX_EOF; + if (NEWLINE_CHARS(ch)) { + S.newline_before = S.newline_before || !in_string; + ++S.line; + S.col = 0; + if (!in_string && ch == "\r" && peek() == "\n") { + // treat a \r\n sequence as a single \n + ++S.pos; + ch = "\n"; + } + } else { + ++S.col; + } + return ch; + }; + + function forward(i) { + while (i-- > 0) next(); + }; + + function looking_at(str) { + return S.text.substr(S.pos, str.length) == str; + }; + + function find_eol() { + var text = S.text; + for (var i = S.pos, n = S.text.length; i < n; ++i) { + var ch = text[i]; + if (NEWLINE_CHARS(ch)) + return i; + } + return -1; + }; + + function find(what, signal_eof) { + var pos = S.text.indexOf(what, S.pos); + if (signal_eof && pos == -1) throw EX_EOF; + return pos; + }; + + function start_token() { + S.tokline = S.line; + S.tokcol = S.col; + S.tokpos = S.pos; + }; + + var prev_was_dot = false; + function token(type, value, is_comment) { + S.regex_allowed = ((type == "operator" && !UNARY_POSTFIX(value)) || + (type == "keyword" && KEYWORDS_BEFORE_EXPRESSION(value)) || + (type == "punc" && PUNC_BEFORE_EXPRESSION(value))); + if (type == "punc" && value == ".") { + prev_was_dot = true; + } else if (!is_comment) { + prev_was_dot = false; + } + var ret = { + type : type, + value : value, + line : S.tokline, + col : S.tokcol, + pos : S.tokpos, + endline : S.line, + endcol : S.col, + endpos : S.pos, + nlb : S.newline_before, + file : filename + }; + if (/^(?:num|string|regexp)$/i.test(type)) { + ret.raw = $TEXT.substring(ret.pos, ret.endpos); + } + if (!is_comment) { + ret.comments_before = S.comments_before; + S.comments_before = []; + // make note of any newlines in the comments that came before + for (var i = 0, len = ret.comments_before.length; i < len; i++) { + ret.nlb = ret.nlb || ret.comments_before[i].nlb; + } + } + S.newline_before = false; + return new AST_Token(ret); + }; + + function skip_whitespace() { + while (WHITESPACE_CHARS(peek())) + next(); + }; + + function read_while(pred) { + var ret = "", ch, i = 0; + while ((ch = peek()) && pred(ch, i++)) + ret += next(); + return ret; + }; + + function parse_error(err) { + js_error(err, filename, S.tokline, S.tokcol, S.tokpos); + }; + + function read_num(prefix) { + var has_e = false, after_e = false, has_x = false, has_dot = prefix == "."; + var num = read_while(function(ch, i){ + var code = ch.charCodeAt(0); + switch (code) { + case 120: case 88: // xX + return has_x ? false : (has_x = true); + case 101: case 69: // eE + return has_x ? true : has_e ? false : (has_e = after_e = true); + case 45: // - + return after_e || (i == 0 && !prefix); + case 43: // + + return after_e; + case (after_e = false, 46): // . + return (!has_dot && !has_x && !has_e) ? (has_dot = true) : false; + } + return is_alphanumeric_char(code); + }); + if (prefix) num = prefix + num; + if (RE_OCT_NUMBER.test(num) && next_token.has_directive("use strict")) { + parse_error("Legacy octal literals are not allowed in strict mode"); + } + var valid = parse_js_number(num); + if (!isNaN(valid)) { + return token("num", valid); + } else { + parse_error("Invalid syntax: " + num); + } + }; + + function read_escaped_char(in_string) { + var ch = next(true, in_string); + switch (ch.charCodeAt(0)) { + case 110 : return "\n"; + case 114 : return "\r"; + case 116 : return "\t"; + case 98 : return "\b"; + case 118 : return "\u000b"; // \v + case 102 : return "\f"; + case 120 : return String.fromCharCode(hex_bytes(2)); // \x + case 117 : return String.fromCharCode(hex_bytes(4)); // \u + case 10 : return ""; // newline + case 13 : // \r + if (peek() == "\n") { // DOS newline + next(true, in_string); + return ""; + } + } + if (ch >= "0" && ch <= "7") + return read_octal_escape_sequence(ch); + return ch; + }; + + function read_octal_escape_sequence(ch) { + // Read + var p = peek(); + if (p >= "0" && p <= "7") { + ch += next(true); + if (ch[0] <= "3" && (p = peek()) >= "0" && p <= "7") + ch += next(true); + } + + // Parse + if (ch === "0") return "\0"; + if (ch.length > 0 && next_token.has_directive("use strict")) + parse_error("Legacy octal escape sequences are not allowed in strict mode"); + return String.fromCharCode(parseInt(ch, 8)); + } + + function hex_bytes(n) { + var num = 0; + for (; n > 0; --n) { + var digit = parseInt(next(true), 16); + if (isNaN(digit)) + parse_error("Invalid hex-character pattern in string"); + num = (num << 4) | digit; + } + return num; + }; + + var read_string = with_eof_error("Unterminated string constant", function(quote_char){ + var quote = next(), ret = ""; + for (;;) { + var ch = next(true, true); + if (ch == "\\") ch = read_escaped_char(true); + else if (NEWLINE_CHARS(ch)) parse_error("Unterminated string constant"); + else if (ch == quote) break; + ret += ch; + } + var tok = token("string", ret); + tok.quote = quote_char; + return tok; + }); + + function skip_line_comment(type) { + var regex_allowed = S.regex_allowed; + var i = find_eol(), ret; + if (i == -1) { + ret = S.text.substr(S.pos); + S.pos = S.text.length; + } else { + ret = S.text.substring(S.pos, i); + S.pos = i; + } + S.col = S.tokcol + (S.pos - S.tokpos); + S.comments_before.push(token(type, ret, true)); + S.regex_allowed = regex_allowed; + return next_token; + }; + + var skip_multiline_comment = with_eof_error("Unterminated multiline comment", function(){ + var regex_allowed = S.regex_allowed; + var i = find("*/", true); + var text = S.text.substring(S.pos, i).replace(/\r\n|\r|\u2028|\u2029/g, '\n'); + // update stream position + forward(text.length /* doesn't count \r\n as 2 char while S.pos - i does */ + 2); + S.comments_before.push(token("comment2", text, true)); + S.regex_allowed = regex_allowed; + return next_token; + }); + + function read_name() { + var backslash = false, name = "", ch, escaped = false, hex; + while ((ch = peek()) != null) { + if (!backslash) { + if (ch == "\\") escaped = backslash = true, next(); + else if (is_identifier_char(ch)) name += next(); + else break; + } + else { + if (ch != "u") parse_error("Expecting UnicodeEscapeSequence -- uXXXX"); + ch = read_escaped_char(); + if (!is_identifier_char(ch)) parse_error("Unicode char: " + ch.charCodeAt(0) + " is not valid in identifier"); + name += ch; + backslash = false; + } + } + if (KEYWORDS(name) && escaped) { + hex = name.charCodeAt(0).toString(16).toUpperCase(); + name = "\\u" + "0000".substr(hex.length) + hex + name.slice(1); + } + return name; + }; + + var read_regexp = with_eof_error("Unterminated regular expression", function(regexp){ + var prev_backslash = false, ch, in_class = false; + while ((ch = next(true))) if (NEWLINE_CHARS(ch)) { + parse_error("Unexpected line terminator"); + } else if (prev_backslash) { + regexp += "\\" + ch; + prev_backslash = false; + } else if (ch == "[") { + in_class = true; + regexp += ch; + } else if (ch == "]" && in_class) { + in_class = false; + regexp += ch; + } else if (ch == "/" && !in_class) { + break; + } else if (ch == "\\") { + prev_backslash = true; + } else { + regexp += ch; + } + var mods = read_name(); + try { + return token("regexp", new RegExp(regexp, mods)); + } catch(e) { + parse_error(e.message); + } + }); + + function read_operator(prefix) { + function grow(op) { + if (!peek()) return op; + var bigger = op + peek(); + if (OPERATORS(bigger)) { + next(); + return grow(bigger); + } else { + return op; + } + }; + return token("operator", grow(prefix || next())); + }; + + function handle_slash() { + next(); + switch (peek()) { + case "/": + next(); + return skip_line_comment("comment1"); + case "*": + next(); + return skip_multiline_comment(); + } + return S.regex_allowed ? read_regexp("") : read_operator("/"); + }; + + function handle_dot() { + next(); + return is_digit(peek().charCodeAt(0)) + ? read_num(".") + : token("punc", "."); + }; + + function read_word() { + var word = read_name(); + if (prev_was_dot) return token("name", word); + return KEYWORDS_ATOM(word) ? token("atom", word) + : !KEYWORDS(word) ? token("name", word) + : OPERATORS(word) ? token("operator", word) + : token("keyword", word); + }; + + function with_eof_error(eof_error, cont) { + return function(x) { + try { + return cont(x); + } catch(ex) { + if (ex === EX_EOF) parse_error(eof_error); + else throw ex; + } + }; + }; + + function next_token(force_regexp) { + if (force_regexp != null) + return read_regexp(force_regexp); + if (shebang && S.pos == 0 && looking_at("#!")) { + start_token(); + forward(2); + skip_line_comment("comment5"); + } + for (;;) { + skip_whitespace(); + start_token(); + if (html5_comments) { + if (looking_at("<!--")) { + forward(4); + skip_line_comment("comment3"); + continue; + } + if (looking_at("-->") && S.newline_before) { + forward(3); + skip_line_comment("comment4"); + continue; + } + } + var ch = peek(); + if (!ch) return token("eof"); + var code = ch.charCodeAt(0); + switch (code) { + case 34: case 39: return read_string(ch); + case 46: return handle_dot(); + case 47: { + var tok = handle_slash(); + if (tok === next_token) continue; + return tok; + } + } + if (is_digit(code)) return read_num(); + if (PUNC_CHARS(ch)) return token("punc", next()); + if (OPERATOR_CHARS(ch)) return read_operator(); + if (code == 92 || is_identifier_start(code)) return read_word(); + break; + } + parse_error("Unexpected character '" + ch + "'"); + }; + + next_token.context = function(nc) { + if (nc) S = nc; + return S; + }; + + next_token.add_directive = function(directive) { + S.directive_stack[S.directive_stack.length - 1].push(directive); + + if (S.directives[directive] === undefined) { + S.directives[directive] = 1; + } else { + S.directives[directive]++; + } + } + + next_token.push_directives_stack = function() { + S.directive_stack.push([]); + } + + next_token.pop_directives_stack = function() { + var directives = S.directive_stack[S.directive_stack.length - 1]; + + for (var i = 0; i < directives.length; i++) { + S.directives[directives[i]]--; + } + + S.directive_stack.pop(); + } + + next_token.has_directive = function(directive) { + return S.directives[directive] !== undefined && + S.directives[directive] > 0; + } + + return next_token; + +}; + +/* -----[ Parser (constants) ]----- */ + +var UNARY_PREFIX = makePredicate([ + "typeof", + "void", + "delete", + "--", + "++", + "!", + "~", + "-", + "+" +]); + +var UNARY_POSTFIX = makePredicate([ "--", "++" ]); + +var ASSIGNMENT = makePredicate([ "=", "+=", "-=", "/=", "*=", "%=", ">>=", "<<=", ">>>=", "|=", "^=", "&=" ]); + +var PRECEDENCE = (function(a, ret){ + for (var i = 0; i < a.length; ++i) { + var b = a[i]; + for (var j = 0; j < b.length; ++j) { + ret[b[j]] = i + 1; + } + } + return ret; +})( + [ + ["||"], + ["&&"], + ["|"], + ["^"], + ["&"], + ["==", "===", "!=", "!=="], + ["<", ">", "<=", ">=", "in", "instanceof"], + [">>", "<<", ">>>"], + ["+", "-"], + ["*", "/", "%"] + ], + {} +); + +var STATEMENTS_WITH_LABELS = array_to_hash([ "for", "do", "while", "switch" ]); + +var ATOMIC_START_TOKEN = array_to_hash([ "atom", "num", "string", "regexp", "name" ]); + +/* -----[ Parser ]----- */ + +function parse($TEXT, options) { + + options = defaults(options, { + bare_returns : false, + cli : false, + expression : false, + filename : null, + html5_comments : true, + shebang : true, + strict : false, + toplevel : null, + }); + + var S = { + input : (typeof $TEXT == "string" + ? tokenizer($TEXT, options.filename, + options.html5_comments, options.shebang) + : $TEXT), + token : null, + prev : null, + peeked : null, + in_function : 0, + in_directives : true, + in_loop : 0, + labels : [] + }; + + S.token = next(); + + function is(type, value) { + return is_token(S.token, type, value); + }; + + function peek() { return S.peeked || (S.peeked = S.input()); }; + + function next() { + S.prev = S.token; + if (S.peeked) { + S.token = S.peeked; + S.peeked = null; + } else { + S.token = S.input(); + } + S.in_directives = S.in_directives && ( + S.token.type == "string" || is("punc", ";") + ); + return S.token; + }; + + function prev() { + return S.prev; + }; + + function croak(msg, line, col, pos) { + var ctx = S.input.context(); + js_error(msg, + ctx.filename, + line != null ? line : ctx.tokline, + col != null ? col : ctx.tokcol, + pos != null ? pos : ctx.tokpos); + }; + + function token_error(token, msg) { + croak(msg, token.line, token.col); + }; + + function unexpected(token) { + if (token == null) + token = S.token; + token_error(token, "Unexpected token: " + token.type + " (" + token.value + ")"); + }; + + function expect_token(type, val) { + if (is(type, val)) { + return next(); + } + token_error(S.token, "Unexpected token " + S.token.type + " «" + S.token.value + "»" + ", expected " + type + " «" + val + "»"); + }; + + function expect(punc) { return expect_token("punc", punc); }; + + function can_insert_semicolon() { + return !options.strict && ( + S.token.nlb || is("eof") || is("punc", "}") + ); + }; + + function semicolon(optional) { + if (is("punc", ";")) next(); + else if (!optional && !can_insert_semicolon()) unexpected(); + }; + + function parenthesised() { + expect("("); + var exp = expression(true); + expect(")"); + return exp; + }; + + function embed_tokens(parser) { + return function() { + var start = S.token; + var expr = parser(); + var end = prev(); + expr.start = start; + expr.end = end; + return expr; + }; + }; + + function handle_regexp() { + if (is("operator", "/") || is("operator", "/=")) { + S.peeked = null; + S.token = S.input(S.token.value.substr(1)); // force regexp + } + }; + + var statement = embed_tokens(function() { + handle_regexp(); + switch (S.token.type) { + case "string": + if (S.in_directives) { + var token = peek(); + if (S.token.raw.indexOf("\\") == -1 + && (token.nlb + || is_token(token, "eof") + || is_token(token, "punc", ";") + || is_token(token, "punc", "}"))) { + S.input.add_directive(S.token.value); + } else { + S.in_directives = false; + } + } + var dir = S.in_directives, stat = simple_statement(); + return dir ? new AST_Directive(stat.body) : stat; + case "num": + case "regexp": + case "operator": + case "atom": + return simple_statement(); + + case "name": + return is_token(peek(), "punc", ":") + ? labeled_statement() + : simple_statement(); + + case "punc": + switch (S.token.value) { + case "{": + return new AST_BlockStatement({ + start : S.token, + body : block_(), + end : prev() + }); + case "[": + case "(": + return simple_statement(); + case ";": + S.in_directives = false; + next(); + return new AST_EmptyStatement(); + default: + unexpected(); + } + + case "keyword": + switch (S.token.value) { + case "break": + next(); + return break_cont(AST_Break); + + case "continue": + next(); + return break_cont(AST_Continue); + + case "debugger": + next(); + semicolon(); + return new AST_Debugger(); + + case "do": + next(); + var body = in_loop(statement); + expect_token("keyword", "while"); + var condition = parenthesised(); + semicolon(true); + return new AST_Do({ + body : body, + condition : condition + }); + + case "while": + next(); + return new AST_While({ + condition : parenthesised(), + body : in_loop(statement) + }); + + case "for": + next(); + return for_(); + + case "function": + next(); + return function_(AST_Defun); + + case "if": + next(); + return if_(); + + case "return": + if (S.in_function == 0 && !options.bare_returns) + croak("'return' outside of function"); + next(); + var value = null; + if (is("punc", ";")) { + next(); + } else if (!can_insert_semicolon()) { + value = expression(true); + semicolon(); + } + return new AST_Return({ + value: value + }); + + case "switch": + next(); + return new AST_Switch({ + expression : parenthesised(), + body : in_loop(switch_body_) + }); + + case "throw": + next(); + if (S.token.nlb) + croak("Illegal newline after 'throw'"); + var value = expression(true); + semicolon(); + return new AST_Throw({ + value: value + }); + + case "try": + next(); + return try_(); + + case "var": + next(); + var node = var_(); + semicolon(); + return node; + + case "const": + next(); + var node = const_(); + semicolon(); + return node; + + case "with": + if (S.input.has_directive("use strict")) { + croak("Strict mode may not include a with statement"); + } + next(); + return new AST_With({ + expression : parenthesised(), + body : statement() + }); + } + } + unexpected(); + }); + + function labeled_statement() { + var label = as_symbol(AST_Label); + if (find_if(function(l){ return l.name == label.name }, S.labels)) { + // ECMA-262, 12.12: An ECMAScript program is considered + // syntactically incorrect if it contains a + // LabelledStatement that is enclosed by a + // LabelledStatement with the same Identifier as label. + croak("Label " + label.name + " defined twice"); + } + expect(":"); + S.labels.push(label); + var stat = statement(); + S.labels.pop(); + if (!(stat instanceof AST_IterationStatement)) { + // check for `continue` that refers to this label. + // those should be reported as syntax errors. + // https://github.com/mishoo/UglifyJS2/issues/287 + label.references.forEach(function(ref){ + if (ref instanceof AST_Continue) { + ref = ref.label.start; + croak("Continue label `" + label.name + "` refers to non-IterationStatement.", + ref.line, ref.col, ref.pos); + } + }); + } + return new AST_LabeledStatement({ body: stat, label: label }); + }; + + function simple_statement(tmp) { + return new AST_SimpleStatement({ body: (tmp = expression(true), semicolon(), tmp) }); + }; + + function break_cont(type) { + var label = null, ldef; + if (!can_insert_semicolon()) { + label = as_symbol(AST_LabelRef, true); + } + if (label != null) { + ldef = find_if(function(l){ return l.name == label.name }, S.labels); + if (!ldef) + croak("Undefined label " + label.name); + label.thedef = ldef; + } + else if (S.in_loop == 0) + croak(type.TYPE + " not inside a loop or switch"); + semicolon(); + var stat = new type({ label: label }); + if (ldef) ldef.references.push(stat); + return stat; + }; + + function for_() { + expect("("); + var init = null; + if (!is("punc", ";")) { + init = is("keyword", "var") + ? (next(), var_(true)) + : expression(true, true); + if (is("operator", "in")) { + if (init instanceof AST_Var && init.definitions.length > 1) + croak("Only one variable declaration allowed in for..in loop"); + next(); + return for_in(init); + } + } + return regular_for(init); + }; + + function regular_for(init) { + expect(";"); + var test = is("punc", ";") ? null : expression(true); + expect(";"); + var step = is("punc", ")") ? null : expression(true); + expect(")"); + return new AST_For({ + init : init, + condition : test, + step : step, + body : in_loop(statement) + }); + }; + + function for_in(init) { + var lhs = init instanceof AST_Var ? init.definitions[0].name : null; + var obj = expression(true); + expect(")"); + return new AST_ForIn({ + init : init, + name : lhs, + object : obj, + body : in_loop(statement) + }); + }; + + var function_ = function(ctor) { + var in_statement = ctor === AST_Defun; + var name = is("name") ? as_symbol(in_statement ? AST_SymbolDefun : AST_SymbolLambda) : null; + if (in_statement && !name) + unexpected(); + expect("("); + return new ctor({ + name: name, + argnames: (function(first, a){ + while (!is("punc", ")")) { + if (first) first = false; else expect(","); + a.push(as_symbol(AST_SymbolFunarg)); + } + next(); + return a; + })(true, []), + body: (function(loop, labels){ + ++S.in_function; + S.in_directives = true; + S.input.push_directives_stack(); + S.in_loop = 0; + S.labels = []; + var a = block_(); + S.input.pop_directives_stack(); + --S.in_function; + S.in_loop = loop; + S.labels = labels; + return a; + })(S.in_loop, S.labels) + }); + }; + + function if_() { + var cond = parenthesised(), body = statement(), belse = null; + if (is("keyword", "else")) { + next(); + belse = statement(); + } + return new AST_If({ + condition : cond, + body : body, + alternative : belse + }); + }; + + function block_() { + expect("{"); + var a = []; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + a.push(statement()); + } + next(); + return a; + }; + + function switch_body_() { + expect("{"); + var a = [], cur = null, branch = null, tmp; + while (!is("punc", "}")) { + if (is("eof")) unexpected(); + if (is("keyword", "case")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Case({ + start : (tmp = S.token, next(), tmp), + expression : expression(true), + body : cur + }); + a.push(branch); + expect(":"); + } + else if (is("keyword", "default")) { + if (branch) branch.end = prev(); + cur = []; + branch = new AST_Default({ + start : (tmp = S.token, next(), expect(":"), tmp), + body : cur + }); + a.push(branch); + } + else { + if (!cur) unexpected(); + cur.push(statement()); + } + } + if (branch) branch.end = prev(); + next(); + return a; + }; + + function try_() { + var body = block_(), bcatch = null, bfinally = null; + if (is("keyword", "catch")) { + var start = S.token; + next(); + expect("("); + var name = as_symbol(AST_SymbolCatch); + expect(")"); + bcatch = new AST_Catch({ + start : start, + argname : name, + body : block_(), + end : prev() + }); + } + if (is("keyword", "finally")) { + var start = S.token; + next(); + bfinally = new AST_Finally({ + start : start, + body : block_(), + end : prev() + }); + } + if (!bcatch && !bfinally) + croak("Missing catch/finally blocks"); + return new AST_Try({ + body : body, + bcatch : bcatch, + bfinally : bfinally + }); + }; + + function vardefs(no_in, in_const) { + var a = []; + for (;;) { + a.push(new AST_VarDef({ + start : S.token, + name : as_symbol(in_const ? AST_SymbolConst : AST_SymbolVar), + value : is("operator", "=") ? (next(), expression(false, no_in)) : null, + end : prev() + })); + if (!is("punc", ",")) + break; + next(); + } + return a; + }; + + var var_ = function(no_in) { + return new AST_Var({ + start : prev(), + definitions : vardefs(no_in, false), + end : prev() + }); + }; + + var const_ = function() { + return new AST_Const({ + start : prev(), + definitions : vardefs(false, true), + end : prev() + }); + }; + + var new_ = function(allow_calls) { + var start = S.token; + expect_token("operator", "new"); + var newexp = expr_atom(false), args; + if (is("punc", "(")) { + next(); + args = expr_list(")"); + } else { + args = []; + } + return subscripts(new AST_New({ + start : start, + expression : newexp, + args : args, + end : prev() + }), allow_calls); + }; + + function as_atom_node() { + var tok = S.token, ret; + switch (tok.type) { + case "name": + case "keyword": + ret = _make_symbol(AST_SymbolRef); + break; + case "num": + ret = new AST_Number({ start: tok, end: tok, value: tok.value }); + break; + case "string": + ret = new AST_String({ + start : tok, + end : tok, + value : tok.value, + quote : tok.quote + }); + break; + case "regexp": + ret = new AST_RegExp({ start: tok, end: tok, value: tok.value }); + break; + case "atom": + switch (tok.value) { + case "false": + ret = new AST_False({ start: tok, end: tok }); + break; + case "true": + ret = new AST_True({ start: tok, end: tok }); + break; + case "null": + ret = new AST_Null({ start: tok, end: tok }); + break; + } + break; + case "operator": + if (!is_identifier_string(tok.value)) { + croak("Invalid getter/setter name: " + tok.value, + tok.line, tok.col, tok.pos); + } + ret = _make_symbol(AST_SymbolRef); + break; + } + next(); + return ret; + }; + + var expr_atom = function(allow_calls) { + if (is("operator", "new")) { + return new_(allow_calls); + } + var start = S.token; + if (is("punc")) { + switch (start.value) { + case "(": + next(); + var ex = expression(true); + ex.start = start; + ex.end = S.token; + expect(")"); + return subscripts(ex, allow_calls); + case "[": + return subscripts(array_(), allow_calls); + case "{": + return subscripts(object_(), allow_calls); + } + unexpected(); + } + if (is("keyword", "function")) { + next(); + var func = function_(AST_Function); + func.start = start; + func.end = prev(); + return subscripts(func, allow_calls); + } + if (ATOMIC_START_TOKEN[S.token.type]) { + return subscripts(as_atom_node(), allow_calls); + } + unexpected(); + }; + + function expr_list(closing, allow_trailing_comma, allow_empty) { + var first = true, a = []; + while (!is("punc", closing)) { + if (first) first = false; else expect(","); + if (allow_trailing_comma && is("punc", closing)) break; + if (is("punc", ",") && allow_empty) { + a.push(new AST_Hole({ start: S.token, end: S.token })); + } else { + a.push(expression(false)); + } + } + next(); + return a; + }; + + var array_ = embed_tokens(function() { + expect("["); + return new AST_Array({ + elements: expr_list("]", !options.strict, true) + }); + }); + + var create_accessor = embed_tokens(function() { + return function_(AST_Accessor); + }); + + var object_ = embed_tokens(function() { + expect("{"); + var first = true, a = []; + while (!is("punc", "}")) { + if (first) first = false; else expect(","); + if (!options.strict && is("punc", "}")) + // allow trailing comma + break; + var start = S.token; + var type = start.type; + var name = as_property_name(); + if (type == "name" && !is("punc", ":")) { + var key = new AST_SymbolAccessor({ + start: S.token, + name: as_property_name(), + end: prev() + }); + if (name == "get") { + a.push(new AST_ObjectGetter({ + start : start, + key : key, + value : create_accessor(), + end : prev() + })); + continue; + } + if (name == "set") { + a.push(new AST_ObjectSetter({ + start : start, + key : key, + value : create_accessor(), + end : prev() + })); + continue; + } + } + expect(":"); + a.push(new AST_ObjectKeyVal({ + start : start, + quote : start.quote, + key : name, + value : expression(false), + end : prev() + })); + } + next(); + return new AST_Object({ properties: a }); + }); + + function as_property_name() { + var tmp = S.token; + switch (tmp.type) { + case "operator": + if (!KEYWORDS(tmp.value)) unexpected(); + case "num": + case "string": + case "name": + case "keyword": + case "atom": + next(); + return tmp.value; + default: + unexpected(); + } + }; + + function as_name() { + var tmp = S.token; + if (tmp.type != "name") unexpected(); + next(); + return tmp.value; + }; + + function _make_symbol(type) { + var name = S.token.value; + return new (name == "this" ? AST_This : type)({ + name : String(name), + start : S.token, + end : S.token + }); + }; + + function as_symbol(type, noerror) { + if (!is("name")) { + if (!noerror) croak("Name expected"); + return null; + } + var sym = _make_symbol(type); + next(); + return sym; + }; + + var subscripts = function(expr, allow_calls) { + var start = expr.start; + if (is("punc", ".")) { + next(); + return subscripts(new AST_Dot({ + start : start, + expression : expr, + property : as_name(), + end : prev() + }), allow_calls); + } + if (is("punc", "[")) { + next(); + var prop = expression(true); + expect("]"); + return subscripts(new AST_Sub({ + start : start, + expression : expr, + property : prop, + end : prev() + }), allow_calls); + } + if (allow_calls && is("punc", "(")) { + next(); + return subscripts(new AST_Call({ + start : start, + expression : expr, + args : expr_list(")"), + end : prev() + }), true); + } + return expr; + }; + + var maybe_unary = function(allow_calls) { + var start = S.token; + if (is("operator") && UNARY_PREFIX(start.value)) { + next(); + handle_regexp(); + var ex = make_unary(AST_UnaryPrefix, start, maybe_unary(allow_calls)); + ex.start = start; + ex.end = prev(); + return ex; + } + var val = expr_atom(allow_calls); + while (is("operator") && UNARY_POSTFIX(S.token.value) && !S.token.nlb) { + val = make_unary(AST_UnaryPostfix, S.token, val); + val.start = start; + val.end = S.token; + next(); + } + return val; + }; + + function make_unary(ctor, token, expr) { + var op = token.value; + if ((op == "++" || op == "--") && !is_assignable(expr)) + croak("Invalid use of " + op + " operator", token.line, token.col, token.pos); + return new ctor({ operator: op, expression: expr }); + }; + + var expr_op = function(left, min_prec, no_in) { + var op = is("operator") ? S.token.value : null; + if (op == "in" && no_in) op = null; + var prec = op != null ? PRECEDENCE[op] : null; + if (prec != null && prec > min_prec) { + next(); + var right = expr_op(maybe_unary(true), prec, no_in); + return expr_op(new AST_Binary({ + start : left.start, + left : left, + operator : op, + right : right, + end : right.end + }), min_prec, no_in); + } + return left; + }; + + function expr_ops(no_in) { + return expr_op(maybe_unary(true), 0, no_in); + }; + + var maybe_conditional = function(no_in) { + var start = S.token; + var expr = expr_ops(no_in); + if (is("operator", "?")) { + next(); + var yes = expression(false); + expect(":"); + return new AST_Conditional({ + start : start, + condition : expr, + consequent : yes, + alternative : expression(false, no_in), + end : prev() + }); + } + return expr; + }; + + function is_assignable(expr) { + if (options.cli) return true; + return expr instanceof AST_PropAccess || expr instanceof AST_SymbolRef; + }; + + var maybe_assign = function(no_in) { + var start = S.token; + var left = maybe_conditional(no_in), val = S.token.value; + if (is("operator") && ASSIGNMENT(val)) { + if (is_assignable(left)) { + next(); + return new AST_Assign({ + start : start, + left : left, + operator : val, + right : maybe_assign(no_in), + end : prev() + }); + } + croak("Invalid assignment"); + } + return left; + }; + + var expression = function(commas, no_in) { + var start = S.token; + var expr = maybe_assign(no_in); + if (commas && is("punc", ",")) { + next(); + return new AST_Seq({ + start : start, + car : expr, + cdr : expression(true, no_in), + end : peek() + }); + } + return expr; + }; + + function in_loop(cont) { + ++S.in_loop; + var ret = cont(); + --S.in_loop; + return ret; + }; + + if (options.expression) { + return expression(true); + } + + return (function(){ + var start = S.token; + var body = []; + S.input.push_directives_stack(); + while (!is("eof")) + body.push(statement()); + S.input.pop_directives_stack(); + var end = prev(); + var toplevel = options.toplevel; + if (toplevel) { + toplevel.body = toplevel.body.concat(body); + toplevel.end = end; + } else { + toplevel = new AST_Toplevel({ start: start, body: body, end: end }); + } + return toplevel; + })(); + +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +// Tree transformer helpers. + +function TreeTransformer(before, after) { + TreeWalker.call(this); + this.before = before; + this.after = after; +} +TreeTransformer.prototype = new TreeWalker; + +(function(undefined){ + + function _(node, descend) { + node.DEFMETHOD("transform", function(tw, in_list){ + var x, y; + tw.push(this); + if (tw.before) x = tw.before(this, descend, in_list); + if (x === undefined) { + if (!tw.after) { + x = this; + descend(x, tw); + } else { + tw.stack[tw.stack.length - 1] = x = this; + descend(x, tw); + y = tw.after(x, in_list); + if (y !== undefined) x = y; + } + } + tw.pop(this); + return x; + }); + }; + + function do_list(list, tw) { + return MAP(list, function(node){ + return node.transform(tw, true); + }); + }; + + _(AST_Node, noop); + + _(AST_LabeledStatement, function(self, tw){ + self.label = self.label.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_SimpleStatement, function(self, tw){ + self.body = self.body.transform(tw); + }); + + _(AST_Block, function(self, tw){ + self.body = do_list(self.body, tw); + }); + + _(AST_DWLoop, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_For, function(self, tw){ + if (self.init) self.init = self.init.transform(tw); + if (self.condition) self.condition = self.condition.transform(tw); + if (self.step) self.step = self.step.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_ForIn, function(self, tw){ + self.init = self.init.transform(tw); + self.object = self.object.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_With, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = self.body.transform(tw); + }); + + _(AST_Exit, function(self, tw){ + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_LoopControl, function(self, tw){ + if (self.label) self.label = self.label.transform(tw); + }); + + _(AST_If, function(self, tw){ + self.condition = self.condition.transform(tw); + self.body = self.body.transform(tw); + if (self.alternative) self.alternative = self.alternative.transform(tw); + }); + + _(AST_Switch, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Case, function(self, tw){ + self.expression = self.expression.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Try, function(self, tw){ + self.body = do_list(self.body, tw); + if (self.bcatch) self.bcatch = self.bcatch.transform(tw); + if (self.bfinally) self.bfinally = self.bfinally.transform(tw); + }); + + _(AST_Catch, function(self, tw){ + self.argname = self.argname.transform(tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Definitions, function(self, tw){ + self.definitions = do_list(self.definitions, tw); + }); + + _(AST_VarDef, function(self, tw){ + self.name = self.name.transform(tw); + if (self.value) self.value = self.value.transform(tw); + }); + + _(AST_Lambda, function(self, tw){ + if (self.name) self.name = self.name.transform(tw); + self.argnames = do_list(self.argnames, tw); + self.body = do_list(self.body, tw); + }); + + _(AST_Call, function(self, tw){ + self.expression = self.expression.transform(tw); + self.args = do_list(self.args, tw); + }); + + _(AST_Seq, function(self, tw){ + self.car = self.car.transform(tw); + self.cdr = self.cdr.transform(tw); + }); + + _(AST_Dot, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Sub, function(self, tw){ + self.expression = self.expression.transform(tw); + self.property = self.property.transform(tw); + }); + + _(AST_Unary, function(self, tw){ + self.expression = self.expression.transform(tw); + }); + + _(AST_Binary, function(self, tw){ + self.left = self.left.transform(tw); + self.right = self.right.transform(tw); + }); + + _(AST_Conditional, function(self, tw){ + self.condition = self.condition.transform(tw); + self.consequent = self.consequent.transform(tw); + self.alternative = self.alternative.transform(tw); + }); + + _(AST_Array, function(self, tw){ + self.elements = do_list(self.elements, tw); + }); + + _(AST_Object, function(self, tw){ + self.properties = do_list(self.properties, tw); + }); + + _(AST_ObjectProperty, function(self, tw){ + self.value = self.value.transform(tw); + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function SymbolDef(scope, index, orig) { + this.name = orig.name; + this.orig = [ orig ]; + this.scope = scope; + this.references = []; + this.global = false; + this.mangled_name = null; + this.undeclared = false; + this.index = index; + this.id = SymbolDef.next_id++; +}; + +SymbolDef.next_id = 1; + +SymbolDef.prototype = { + unmangleable: function(options) { + if (!options) options = {}; + + return (this.global && !options.toplevel) + || this.undeclared + || (!options.eval && (this.scope.uses_eval || this.scope.uses_with)) + || (options.keep_fnames + && (this.orig[0] instanceof AST_SymbolLambda + || this.orig[0] instanceof AST_SymbolDefun)); + }, + mangle: function(options) { + var cache = options.cache && options.cache.props; + if (this.global && cache && cache.has(this.name)) { + this.mangled_name = cache.get(this.name); + } + else if (!this.mangled_name && !this.unmangleable(options)) { + var s = this.scope; + var sym = this.orig[0]; + if (!options.screw_ie8 && sym instanceof AST_SymbolLambda) + s = s.parent_scope; + var def; + if (this.defun && (def = this.defun.variables.get(this.name))) { + this.mangled_name = def.mangled_name || def.name; + } else + this.mangled_name = s.next_mangled(options, this); + if (this.global && cache) { + cache.set(this.name, this.mangled_name); + } + } + } +}; + +AST_Toplevel.DEFMETHOD("figure_out_scope", function(options){ + options = defaults(options, { + cache: null, + screw_ie8: true, + }); + + // pass 1: setup scope chaining and handle definitions + var self = this; + var scope = self.parent_scope = null; + var labels = new Dictionary(); + var defun = null; + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Catch) { + var save_scope = scope; + scope = new AST_Scope(node); + scope.init_scope_vars(save_scope); + descend(); + scope = save_scope; + return true; + } + if (node instanceof AST_Scope) { + node.init_scope_vars(scope); + var save_scope = scope; + var save_defun = defun; + var save_labels = labels; + defun = scope = node; + labels = new Dictionary(); + descend(); + scope = save_scope; + defun = save_defun; + labels = save_labels; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_LabeledStatement) { + var l = node.label; + if (labels.has(l.name)) { + throw new Error(string_template("Label {name} defined twice", l)); + } + labels.set(l.name, l); + descend(); + labels.del(l.name); + return true; // no descend again + } + if (node instanceof AST_With) { + for (var s = scope; s; s = s.parent_scope) + s.uses_with = true; + return; + } + if (node instanceof AST_Symbol) { + node.scope = scope; + } + if (node instanceof AST_Label) { + node.thedef = node; + node.references = []; + } + if (node instanceof AST_SymbolLambda) { + defun.def_function(node); + } + else if (node instanceof AST_SymbolDefun) { + // Careful here, the scope where this should be defined is + // the parent scope. The reason is that we enter a new + // scope when we encounter the AST_Defun node (which is + // instanceof AST_Scope) but we get to the symbol a bit + // later. + (node.scope = defun.parent_scope).def_function(node); + } + else if (node instanceof AST_SymbolVar + || node instanceof AST_SymbolConst) { + defun.def_variable(node); + if (defun !== scope) { + node.mark_enclosed(options); + var def = scope.find_variable(node); + if (node.thedef !== def) { + node.thedef = def; + node.reference(options); + } + } + } + else if (node instanceof AST_SymbolCatch) { + scope.def_variable(node).defun = defun; + } + else if (node instanceof AST_LabelRef) { + var sym = labels.get(node.name); + if (!sym) throw new Error(string_template("Undefined label {name} [{line},{col}]", { + name: node.name, + line: node.start.line, + col: node.start.col + })); + node.thedef = sym; + } + }); + self.walk(tw); + + // pass 2: find back references and eval + var func = null; + var globals = self.globals = new Dictionary(); + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_Lambda) { + var prev_func = func; + func = node; + descend(); + func = prev_func; + return true; + } + if (node instanceof AST_LoopControl && node.label) { + node.label.thedef.references.push(node); + return true; + } + if (node instanceof AST_SymbolRef) { + var name = node.name; + if (name == "eval" && tw.parent() instanceof AST_Call) { + for (var s = node.scope; s && !s.uses_eval; s = s.parent_scope) { + s.uses_eval = true; + } + } + var sym = node.scope.find_variable(name); + if (node.scope instanceof AST_Lambda && name == "arguments") { + node.scope.uses_arguments = true; + } + if (!sym) { + sym = self.def_global(node); + } + node.thedef = sym; + node.reference(options); + return true; + } + }); + self.walk(tw); + + // pass 3: fix up any scoping issue with IE8 + if (!options.screw_ie8) { + self.walk(new TreeWalker(function(node, descend) { + if (node instanceof AST_SymbolCatch) { + var name = node.name; + var refs = node.thedef.references; + var scope = node.thedef.defun; + var def = scope.find_variable(name) || self.globals.get(name) || scope.def_variable(node); + refs.forEach(function(ref) { + ref.thedef = def; + ref.reference(options); + }); + node.thedef = def; + return true; + } + })); + } + + if (options.cache) { + this.cname = options.cache.cname; + } +}); + +AST_Toplevel.DEFMETHOD("def_global", function(node){ + var globals = this.globals, name = node.name; + if (globals.has(name)) { + return globals.get(name); + } else { + var g = new SymbolDef(this, globals.size(), node); + g.undeclared = true; + g.global = true; + globals.set(name, g); + return g; + } +}); + +AST_Scope.DEFMETHOD("init_scope_vars", function(parent_scope){ + this.variables = new Dictionary(); // map name to AST_SymbolVar (variables defined in this scope; includes functions) + this.functions = new Dictionary(); // map name to AST_SymbolDefun (functions defined in this scope) + this.uses_with = false; // will be set to true if this or some nested scope uses the `with` statement + this.uses_eval = false; // will be set to true if this or nested scope uses the global `eval` + this.parent_scope = parent_scope; // the parent scope + this.enclosed = []; // a list of variables from this or outer scope(s) that are referenced from this or inner scopes + this.cname = -1; // the current index for mangling functions/variables +}); + +AST_Lambda.DEFMETHOD("init_scope_vars", function(){ + AST_Scope.prototype.init_scope_vars.apply(this, arguments); + this.uses_arguments = false; + this.def_variable(new AST_SymbolVar({ + name: "arguments", + start: this.start, + end: this.end + })); +}); + +AST_Symbol.DEFMETHOD("mark_enclosed", function(options) { + var def = this.definition(); + var s = this.scope; + while (s) { + push_uniq(s.enclosed, def); + if (options.keep_fnames) { + s.functions.each(function(d) { + push_uniq(def.scope.enclosed, d); + }); + } + if (s === def.scope) break; + s = s.parent_scope; + } +}); + +AST_Symbol.DEFMETHOD("reference", function(options) { + this.definition().references.push(this); + this.mark_enclosed(options); +}); + +AST_Scope.DEFMETHOD("find_variable", function(name){ + if (name instanceof AST_Symbol) name = name.name; + return this.variables.get(name) + || (this.parent_scope && this.parent_scope.find_variable(name)); +}); + +AST_Scope.DEFMETHOD("def_function", function(symbol){ + this.functions.set(symbol.name, this.def_variable(symbol)); +}); + +AST_Scope.DEFMETHOD("def_variable", function(symbol){ + var def; + if (!this.variables.has(symbol.name)) { + def = new SymbolDef(this, this.variables.size(), symbol); + this.variables.set(symbol.name, def); + def.global = !this.parent_scope; + } else { + def = this.variables.get(symbol.name); + def.orig.push(symbol); + } + return symbol.thedef = def; +}); + +AST_Scope.DEFMETHOD("next_mangled", function(options){ + var ext = this.enclosed; + out: while (true) { + var m = base54(++this.cname); + if (!is_identifier(m)) continue; // skip over "do" + + // https://github.com/mishoo/UglifyJS2/issues/242 -- do not + // shadow a name excepted from mangling. + if (options.except.indexOf(m) >= 0) continue; + + // we must ensure that the mangled name does not shadow a name + // from some parent scope that is referenced in this or in + // inner scopes. + for (var i = ext.length; --i >= 0;) { + var sym = ext[i]; + var name = sym.mangled_name || (sym.unmangleable(options) && sym.name); + if (m == name) continue out; + } + return m; + } +}); + +AST_Function.DEFMETHOD("next_mangled", function(options, def){ + // #179, #326 + // in Safari strict mode, something like (function x(x){...}) is a syntax error; + // a function expression's argument cannot shadow the function expression's name + + var tricky_def = def.orig[0] instanceof AST_SymbolFunarg && this.name && this.name.definition(); + + // the function's mangled_name is null when keep_fnames is true + var tricky_name = tricky_def ? tricky_def.mangled_name || tricky_def.name : null; + + while (true) { + var name = AST_Lambda.prototype.next_mangled.call(this, options, def); + if (!tricky_name || tricky_name != name) + return name; + } +}); + +AST_Symbol.DEFMETHOD("unmangleable", function(options){ + return this.definition().unmangleable(options); +}); + +// labels are always mangleable +AST_Label.DEFMETHOD("unmangleable", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("unreferenced", function(){ + return this.definition().references.length == 0 + && !(this.scope.uses_eval || this.scope.uses_with); +}); + +AST_Symbol.DEFMETHOD("undeclared", function(){ + return this.definition().undeclared; +}); + +AST_LabelRef.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Label.DEFMETHOD("undeclared", function(){ + return false; +}); + +AST_Symbol.DEFMETHOD("definition", function(){ + return this.thedef; +}); + +AST_Symbol.DEFMETHOD("global", function(){ + return this.definition().global; +}); + +AST_Toplevel.DEFMETHOD("_default_mangler_options", function(options){ + return defaults(options, { + eval : false, + except : [], + keep_fnames : false, + screw_ie8 : true, + sort : false, // Ignored. Flag retained for backwards compatibility. + toplevel : false, + }); +}); + +AST_Toplevel.DEFMETHOD("mangle_names", function(options){ + options = this._default_mangler_options(options); + + // Never mangle arguments + options.except.push('arguments'); + + // We only need to mangle declaration nodes. Special logic wired + // into the code generator will display the mangled name if it's + // present (and for AST_SymbolRef-s it'll use the mangled name of + // the AST_SymbolDeclaration that it points to). + var lname = -1; + var to_mangle = []; + + if (options.cache) { + this.globals.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + to_mangle.push(symbol); + } + }); + } + + var tw = new TreeWalker(function(node, descend){ + if (node instanceof AST_LabeledStatement) { + // lname is incremented when we get to the AST_Label + var save_nesting = lname; + descend(); + lname = save_nesting; + return true; // don't descend again in TreeWalker + } + if (node instanceof AST_Scope) { + var p = tw.parent(), a = []; + node.variables.each(function(symbol){ + if (options.except.indexOf(symbol.name) < 0) { + a.push(symbol); + } + }); + to_mangle.push.apply(to_mangle, a); + return; + } + if (node instanceof AST_Label) { + var name; + do name = base54(++lname); while (!is_identifier(name)); + node.mangled_name = name; + return true; + } + if (options.screw_ie8 && node instanceof AST_SymbolCatch) { + to_mangle.push(node.definition()); + return; + } + }); + this.walk(tw); + to_mangle.forEach(function(def){ def.mangle(options) }); + + if (options.cache) { + options.cache.cname = this.cname; + } +}); + +AST_Toplevel.DEFMETHOD("compute_char_frequency", function(options){ + options = this._default_mangler_options(options); + var tw = new TreeWalker(function(node){ + if (node instanceof AST_Constant) + base54.consider(node.print_to_string()); + else if (node instanceof AST_Return) + base54.consider("return"); + else if (node instanceof AST_Throw) + base54.consider("throw"); + else if (node instanceof AST_Continue) + base54.consider("continue"); + else if (node instanceof AST_Break) + base54.consider("break"); + else if (node instanceof AST_Debugger) + base54.consider("debugger"); + else if (node instanceof AST_Directive) + base54.consider(node.value); + else if (node instanceof AST_While) + base54.consider("while"); + else if (node instanceof AST_Do) + base54.consider("do while"); + else if (node instanceof AST_If) { + base54.consider("if"); + if (node.alternative) base54.consider("else"); + } + else if (node instanceof AST_Var) + base54.consider("var"); + else if (node instanceof AST_Const) + base54.consider("const"); + else if (node instanceof AST_Lambda) + base54.consider("function"); + else if (node instanceof AST_For) + base54.consider("for"); + else if (node instanceof AST_ForIn) + base54.consider("for in"); + else if (node instanceof AST_Switch) + base54.consider("switch"); + else if (node instanceof AST_Case) + base54.consider("case"); + else if (node instanceof AST_Default) + base54.consider("default"); + else if (node instanceof AST_With) + base54.consider("with"); + else if (node instanceof AST_ObjectSetter) + base54.consider("set" + node.key); + else if (node instanceof AST_ObjectGetter) + base54.consider("get" + node.key); + else if (node instanceof AST_ObjectKeyVal) + base54.consider(node.key); + else if (node instanceof AST_New) + base54.consider("new"); + else if (node instanceof AST_This) + base54.consider("this"); + else if (node instanceof AST_Try) + base54.consider("try"); + else if (node instanceof AST_Catch) + base54.consider("catch"); + else if (node instanceof AST_Finally) + base54.consider("finally"); + else if (node instanceof AST_Symbol && node.unmangleable(options)) + base54.consider(node.name); + else if (node instanceof AST_Unary || node instanceof AST_Binary) + base54.consider(node.operator); + else if (node instanceof AST_Dot) + base54.consider(node.property); + }); + this.walk(tw); + base54.sort(); +}); + +var base54 = (function() { + var string = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_0123456789"; + var chars, frequency; + function reset() { + frequency = Object.create(null); + chars = string.split("").map(function(ch){ return ch.charCodeAt(0) }); + chars.forEach(function(ch){ frequency[ch] = 0 }); + } + base54.consider = function(str){ + for (var i = str.length; --i >= 0;) { + var code = str.charCodeAt(i); + if (code in frequency) ++frequency[code]; + } + }; + base54.sort = function() { + chars = mergeSort(chars, function(a, b){ + if (is_digit(a) && !is_digit(b)) return 1; + if (is_digit(b) && !is_digit(a)) return -1; + return frequency[b] - frequency[a]; + }); + }; + base54.reset = reset; + reset(); + base54.get = function(){ return chars }; + base54.freq = function(){ return frequency }; + function base54(num) { + var ret = "", base = 54; + num++; + do { + num--; + ret += String.fromCharCode(chars[num % base]); + num = Math.floor(num / base); + base = 64; + } while (num > 0); + return ret; + }; + return base54; +})(); + +AST_Toplevel.DEFMETHOD("scope_warnings", function(options){ + options = defaults(options, { + assign_to_global : true, + eval : true, + func_arguments : true, + nested_defuns : true, + undeclared : false, // this makes a lot of noise + unreferenced : true, + }); + var tw = new TreeWalker(function(node){ + if (options.undeclared + && node instanceof AST_SymbolRef + && node.undeclared()) + { + // XXX: this also warns about JS standard names, + // i.e. Object, Array, parseInt etc. Should add a list of + // exceptions. + AST_Node.warn("Undeclared symbol: {name} [{file}:{line},{col}]", { + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.assign_to_global) + { + var sym = null; + if (node instanceof AST_Assign && node.left instanceof AST_SymbolRef) + sym = node.left; + else if (node instanceof AST_ForIn && node.init instanceof AST_SymbolRef) + sym = node.init; + if (sym + && (sym.undeclared() + || (sym.global() && sym.scope !== sym.definition().scope))) { + AST_Node.warn("{msg}: {name} [{file}:{line},{col}]", { + msg: sym.undeclared() ? "Accidental global?" : "Assignment to global", + name: sym.name, + file: sym.start.file, + line: sym.start.line, + col: sym.start.col + }); + } + } + if (options.eval + && node instanceof AST_SymbolRef + && node.undeclared() + && node.name == "eval") { + AST_Node.warn("Eval is used [{file}:{line},{col}]", node.start); + } + if (options.unreferenced + && (node instanceof AST_SymbolDeclaration || node instanceof AST_Label) + && !(node instanceof AST_SymbolCatch) + && node.unreferenced()) { + AST_Node.warn("{type} {name} is declared but not referenced [{file}:{line},{col}]", { + type: node instanceof AST_Label ? "Label" : "Symbol", + name: node.name, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.func_arguments + && node instanceof AST_Lambda + && node.uses_arguments) { + AST_Node.warn("arguments used in function {name} [{file}:{line},{col}]", { + name: node.name ? node.name.name : "anonymous", + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + if (options.nested_defuns + && node instanceof AST_Defun + && !(tw.parent() instanceof AST_Scope)) { + AST_Node.warn("Function {name} declared in nested statement \"{type}\" [{file}:{line},{col}]", { + name: node.name.name, + type: tw.parent().TYPE, + file: node.start.file, + line: node.start.line, + col: node.start.col + }); + } + }); + this.walk(tw); +}); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +var EXPECT_DIRECTIVE = /^$|[;{][\s\n]*$/; + +function is_some_comments(comment) { + // multiline comment + return comment.type == "comment2" && /@preserve|@license|@cc_on/i.test(comment.value); +} + +function OutputStream(options) { + + options = defaults(options, { + ascii_only : false, + beautify : false, + bracketize : false, + comments : false, + indent_level : 4, + indent_start : 0, + inline_script : true, + keep_quoted_props: false, + max_line_len : false, + preamble : null, + preserve_line : false, + quote_keys : false, + quote_style : 0, + screw_ie8 : true, + semicolons : true, + shebang : true, + source_map : null, + space_colon : true, + unescape_regexps : false, + width : 80, + wrap_iife : false, + }, true); + + // Convert comment option to RegExp if neccessary and set up comments filter + var comment_filter = return_false; // Default case, throw all comments away + if (options.comments) { + var comments = options.comments; + if (typeof options.comments === "string" && /^\/.*\/[a-zA-Z]*$/.test(options.comments)) { + var regex_pos = options.comments.lastIndexOf("/"); + comments = new RegExp( + options.comments.substr(1, regex_pos - 1), + options.comments.substr(regex_pos + 1) + ); + } + if (comments instanceof RegExp) { + comment_filter = function(comment) { + return comment.type != "comment5" && comments.test(comment.value); + }; + } + else if (typeof comments === "function") { + comment_filter = function(comment) { + return comment.type != "comment5" && comments(this, comment); + }; + } + else if (comments === "some") { + comment_filter = is_some_comments; + } else { // NOTE includes "all" option + comment_filter = return_true; + } + } + + var indentation = 0; + var current_col = 0; + var current_line = 1; + var current_pos = 0; + var OUTPUT = ""; + + function to_ascii(str, identifier) { + return str.replace(/[\u0000-\u001f\u007f-\uffff]/g, function(ch) { + var code = ch.charCodeAt(0).toString(16); + if (code.length <= 2 && !identifier) { + while (code.length < 2) code = "0" + code; + return "\\x" + code; + } else { + while (code.length < 4) code = "0" + code; + return "\\u" + code; + } + }); + }; + + function make_string(str, quote) { + var dq = 0, sq = 0; + str = str.replace(/[\\\b\f\n\r\v\t\x22\x27\u2028\u2029\0\ufeff]/g, + function(s, i){ + switch (s) { + case '"': ++dq; return '"'; + case "'": ++sq; return "'"; + case "\\": return "\\\\"; + case "\n": return "\\n"; + case "\r": return "\\r"; + case "\t": return "\\t"; + case "\b": return "\\b"; + case "\f": return "\\f"; + case "\x0B": return options.screw_ie8 ? "\\v" : "\\x0B"; + case "\u2028": return "\\u2028"; + case "\u2029": return "\\u2029"; + case "\ufeff": return "\\ufeff"; + case "\0": + return /[0-7]/.test(str.charAt(i+1)) ? "\\x00" : "\\0"; + } + return s; + }); + function quote_single() { + return "'" + str.replace(/\x27/g, "\\'") + "'"; + } + function quote_double() { + return '"' + str.replace(/\x22/g, '\\"') + '"'; + } + if (options.ascii_only) str = to_ascii(str); + switch (options.quote_style) { + case 1: + return quote_single(); + case 2: + return quote_double(); + case 3: + return quote == "'" ? quote_single() : quote_double(); + default: + return dq > sq ? quote_single() : quote_double(); + } + }; + + function encode_string(str, quote) { + var ret = make_string(str, quote); + if (options.inline_script) { + ret = ret.replace(/<\x2fscript([>\/\t\n\f\r ])/gi, "<\\/script$1"); + ret = ret.replace(/\x3c!--/g, "\\x3c!--"); + ret = ret.replace(/--\x3e/g, "--\\x3e"); + } + return ret; + }; + + function make_name(name) { + name = name.toString(); + if (options.ascii_only) + name = to_ascii(name, true); + return name; + }; + + function make_indent(back) { + return repeat_string(" ", options.indent_start + indentation - back * options.indent_level); + }; + + /* -----[ beautification/minification ]----- */ + + var might_need_space = false; + var might_need_semicolon = false; + var might_add_newline = 0; + var last = ""; + + var ensure_line_len = options.max_line_len ? function() { + if (current_col > options.max_line_len) { + if (might_add_newline) { + var left = OUTPUT.slice(0, might_add_newline); + var right = OUTPUT.slice(might_add_newline); + OUTPUT = left + "\n" + right; + current_line++; + current_pos++; + current_col = right.length; + } + if (current_col > options.max_line_len) { + AST_Node.warn("Output exceeds {max_line_len} characters", options); + } + } + might_add_newline = 0; + } : noop; + + var requireSemicolonChars = makePredicate("( [ + * / - , ."); + + function print(str) { + str = String(str); + var ch = str.charAt(0); + var prev = last.charAt(last.length - 1); + if (might_need_semicolon) { + might_need_semicolon = false; + + if (prev == ":" && ch == "}" || (!ch || ";}".indexOf(ch) < 0) && prev != ";") { + if (options.semicolons || requireSemicolonChars(ch)) { + OUTPUT += ";"; + current_col++; + current_pos++; + } else { + ensure_line_len(); + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + + if (/^\s+$/.test(str)) { + // reset the semicolon flag, since we didn't print one + // now and might still have to later + might_need_semicolon = true; + } + } + + if (!options.beautify) + might_need_space = false; + } + } + + if (!options.beautify && options.preserve_line && stack[stack.length - 1]) { + var target_line = stack[stack.length - 1].start.line; + while (current_line < target_line) { + ensure_line_len(); + OUTPUT += "\n"; + current_pos++; + current_line++; + current_col = 0; + might_need_space = false; + } + } + + if (might_need_space) { + if ((is_identifier_char(prev) + && (is_identifier_char(ch) || ch == "\\")) + || (ch == "/" && ch == prev) + || ((ch == "+" || ch == "-") && ch == last)) + { + OUTPUT += " "; + current_col++; + current_pos++; + } + might_need_space = false; + } + OUTPUT += str; + current_pos += str.length; + var a = str.split(/\r?\n/), n = a.length - 1; + current_line += n; + current_col += a[0].length; + if (n > 0) { + ensure_line_len(); + current_col = a[n].length; + } + last = str; + }; + + var space = options.beautify ? function() { + print(" "); + } : function() { + might_need_space = true; + }; + + var indent = options.beautify ? function(half) { + if (options.beautify) { + print(make_indent(half ? 0.5 : 0)); + } + } : noop; + + var with_indent = options.beautify ? function(col, cont) { + if (col === true) col = next_indent(); + var save_indentation = indentation; + indentation = col; + var ret = cont(); + indentation = save_indentation; + return ret; + } : function(col, cont) { return cont() }; + + var newline = options.beautify ? function() { + print("\n"); + } : options.max_line_len ? function() { + ensure_line_len(); + might_add_newline = OUTPUT.length; + } : noop; + + var semicolon = options.beautify ? function() { + print(";"); + } : function() { + might_need_semicolon = true; + }; + + function force_semicolon() { + might_need_semicolon = false; + print(";"); + }; + + function next_indent() { + return indentation + options.indent_level; + }; + + function with_block(cont) { + var ret; + print("{"); + newline(); + with_indent(next_indent(), function(){ + ret = cont(); + }); + indent(); + print("}"); + return ret; + }; + + function with_parens(cont) { + print("("); + //XXX: still nice to have that for argument lists + //var ret = with_indent(current_col, cont); + var ret = cont(); + print(")"); + return ret; + }; + + function with_square(cont) { + print("["); + //var ret = with_indent(current_col, cont); + var ret = cont(); + print("]"); + return ret; + }; + + function comma() { + print(","); + space(); + }; + + function colon() { + print(":"); + if (options.space_colon) space(); + }; + + var add_mapping = options.source_map ? function(token, name) { + try { + if (token) options.source_map.add( + token.file || "?", + current_line, current_col, + token.line, token.col, + (!name && token.type == "name") ? token.value : name + ); + } catch(ex) { + AST_Node.warn("Couldn't figure out mapping for {file}:{line},{col} → {cline},{ccol} [{name}]", { + file: token.file, + line: token.line, + col: token.col, + cline: current_line, + ccol: current_col, + name: name || "" + }) + } + } : noop; + + function get() { + if (might_add_newline) { + ensure_line_len(); + } + return OUTPUT; + }; + + var stack = []; + return { + get : get, + toString : get, + indent : indent, + indentation : function() { return indentation }, + current_width : function() { return current_col - indentation }, + should_break : function() { return options.width && this.current_width() >= options.width }, + newline : newline, + print : print, + space : space, + comma : comma, + colon : colon, + last : function() { return last }, + semicolon : semicolon, + force_semicolon : force_semicolon, + to_ascii : to_ascii, + print_name : function(name) { print(make_name(name)) }, + print_string : function(str, quote, escape_directive) { + var encoded = encode_string(str, quote); + if (escape_directive === true && encoded.indexOf("\\") === -1) { + // Insert semicolons to break directive prologue + if (!EXPECT_DIRECTIVE.test(OUTPUT)) { + force_semicolon(); + } + force_semicolon(); + } + print(encoded); + }, + encode_string : encode_string, + next_indent : next_indent, + with_indent : with_indent, + with_block : with_block, + with_parens : with_parens, + with_square : with_square, + add_mapping : add_mapping, + option : function(opt) { return options[opt] }, + comment_filter : comment_filter, + line : function() { return current_line }, + col : function() { return current_col }, + pos : function() { return current_pos }, + push_node : function(node) { stack.push(node) }, + pop_node : function() { return stack.pop() }, + parent : function(n) { + return stack[stack.length - 2 - (n || 0)]; + } + }; + +}; + +/* -----[ code generators ]----- */ + +(function(){ + + /* -----[ utils ]----- */ + + function DEFPRINT(nodetype, generator) { + nodetype.DEFMETHOD("_codegen", generator); + }; + + var use_asm = false; + var in_directive = false; + + AST_Node.DEFMETHOD("print", function(stream, force_parens){ + var self = this, generator = self._codegen, prev_use_asm = use_asm; + if (self instanceof AST_Directive && self.value == "use asm" && stream.parent() instanceof AST_Scope) { + use_asm = true; + } + function doit() { + self.add_comments(stream); + self.add_source_map(stream); + generator(self, stream); + } + stream.push_node(self); + if (force_parens || self.needs_parens(stream)) { + stream.with_parens(doit); + } else { + doit(); + } + stream.pop_node(); + if (self instanceof AST_Scope) { + use_asm = prev_use_asm; + } + }); + + AST_Node.DEFMETHOD("print_to_string", function(options){ + var s = OutputStream(options); + if (!options) s._readonly = true; + this.print(s); + return s.get(); + }); + + /* -----[ comments ]----- */ + + AST_Node.DEFMETHOD("add_comments", function(output){ + if (output._readonly) return; + var self = this; + var start = self.start; + if (start && !start._comments_dumped) { + start._comments_dumped = true; + var comments = start.comments_before || []; + + // XXX: ugly fix for https://github.com/mishoo/UglifyJS2/issues/112 + // and https://github.com/mishoo/UglifyJS2/issues/372 + if (self instanceof AST_Exit && self.value) { + self.value.walk(new TreeWalker(function(node){ + if (node.start && node.start.comments_before) { + comments = comments.concat(node.start.comments_before); + node.start.comments_before = []; + } + if (node instanceof AST_Function || + node instanceof AST_Array || + node instanceof AST_Object) + { + return true; // don't go inside. + } + })); + } + + if (output.pos() == 0) { + if (comments.length > 0 && output.option("shebang") && comments[0].type == "comment5") { + output.print("#!" + comments.shift().value + "\n"); + output.indent(); + } + var preamble = output.option("preamble"); + if (preamble) { + output.print(preamble.replace(/\r\n?|[\n\u2028\u2029]|\s*$/g, "\n")); + } + } + + comments = comments.filter(output.comment_filter, self); + + // Keep single line comments after nlb, after nlb + if (!output.option("beautify") && comments.length > 0 && + /comment[134]/.test(comments[0].type) && + output.col() !== 0 && comments[0].nlb) + { + output.print("\n"); + } + + comments.forEach(function(c){ + if (/comment[134]/.test(c.type)) { + output.print("//" + c.value + "\n"); + output.indent(); + } + else if (c.type == "comment2") { + output.print("/*" + c.value + "*/"); + if (start.nlb) { + output.print("\n"); + output.indent(); + } else { + output.space(); + } + } + }); + } + }); + + /* -----[ PARENTHESES ]----- */ + + function PARENS(nodetype, func) { + if (Array.isArray(nodetype)) { + nodetype.forEach(function(nodetype){ + PARENS(nodetype, func); + }); + } else { + nodetype.DEFMETHOD("needs_parens", func); + } + }; + + PARENS(AST_Node, function(){ + return false; + }); + + // a function expression needs parens around it when it's provably + // the first token to appear in a statement. + PARENS(AST_Function, function(output){ + if (first_in_statement(output)) { + return true; + } + + if (output.option('wrap_iife')) { + var p = output.parent(); + return p instanceof AST_Call && p.expression === this; + } + + return false; + }); + + // same goes for an object literal, because otherwise it would be + // interpreted as a block of code. + PARENS(AST_Object, function(output){ + return first_in_statement(output); + }); + + PARENS(AST_Unary, function(output){ + var p = output.parent(); + return p instanceof AST_PropAccess && p.expression === this + || p instanceof AST_Call && p.expression === this; + }); + + PARENS(AST_Seq, function(output){ + var p = output.parent(); + return p instanceof AST_Call // (foo, bar)() or foo(1, (2, 3), 4) + || p instanceof AST_Unary // !(foo, bar, baz) + || p instanceof AST_Binary // 1 + (2, 3) + 4 ==> 8 + || p instanceof AST_VarDef // var a = (1, 2), b = a + a; ==> b == 4 + || p instanceof AST_PropAccess // (1, {foo:2}).foo or (1, {foo:2})["foo"] ==> 2 + || p instanceof AST_Array // [ 1, (2, 3), 4 ] ==> [ 1, 3, 4 ] + || p instanceof AST_ObjectProperty // { foo: (1, 2) }.foo ==> 2 + || p instanceof AST_Conditional /* (false, true) ? (a = 10, b = 20) : (c = 30) + * ==> 20 (side effect, set a := 10 and b := 20) */ + ; + }); + + PARENS(AST_Binary, function(output){ + var p = output.parent(); + // (foo && bar)() + if (p instanceof AST_Call && p.expression === this) + return true; + // typeof (foo && bar) + if (p instanceof AST_Unary) + return true; + // (foo && bar)["prop"], (foo && bar).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + // this deals with precedence: 3 * (2 + 1) + if (p instanceof AST_Binary) { + var po = p.operator, pp = PRECEDENCE[po]; + var so = this.operator, sp = PRECEDENCE[so]; + if (pp > sp + || (pp == sp + && this === p.right)) { + return true; + } + } + }); + + PARENS(AST_PropAccess, function(output){ + var p = output.parent(); + if (p instanceof AST_New && p.expression === this) { + // i.e. new (foo.bar().baz) + // + // if there's one call into this subtree, then we need + // parens around it too, otherwise the call will be + // interpreted as passing the arguments to the upper New + // expression. + try { + this.walk(new TreeWalker(function(node){ + if (node instanceof AST_Call) throw p; + })); + } catch(ex) { + if (ex !== p) throw ex; + return true; + } + } + }); + + PARENS(AST_Call, function(output){ + var p = output.parent(), p1; + if (p instanceof AST_New && p.expression === this) + return true; + + // workaround for Safari bug. + // https://bugs.webkit.org/show_bug.cgi?id=123506 + return this.expression instanceof AST_Function + && p instanceof AST_PropAccess + && p.expression === this + && (p1 = output.parent(1)) instanceof AST_Assign + && p1.left === p; + }); + + PARENS(AST_New, function(output){ + var p = output.parent(); + if (!need_constructor_parens(this, output) + && (p instanceof AST_PropAccess // (new Date).getTime(), (new Date)["getTime"]() + || p instanceof AST_Call && p.expression === this)) // (new foo)(bar) + return true; + }); + + PARENS(AST_Number, function(output){ + var p = output.parent(); + if (p instanceof AST_PropAccess && p.expression === this) { + var value = this.getValue(); + if (value < 0 || /^0/.test(make_num(value))) { + return true; + } + } + }); + + PARENS([ AST_Assign, AST_Conditional ], function (output){ + var p = output.parent(); + // !(a = false) → true + if (p instanceof AST_Unary) + return true; + // 1 + (a = 2) + 3 → 6, side effect setting a = 2 + if (p instanceof AST_Binary && !(p instanceof AST_Assign)) + return true; + // (a = func)() —or— new (a = Object)() + if (p instanceof AST_Call && p.expression === this) + return true; + // (a = foo) ? bar : baz + if (p instanceof AST_Conditional && p.condition === this) + return true; + // (a = foo)["prop"] —or— (a = foo).prop + if (p instanceof AST_PropAccess && p.expression === this) + return true; + }); + + /* -----[ PRINTERS ]----- */ + + DEFPRINT(AST_Directive, function(self, output){ + output.print_string(self.value, self.quote); + output.semicolon(); + }); + DEFPRINT(AST_Debugger, function(self, output){ + output.print("debugger"); + output.semicolon(); + }); + + /* -----[ statements ]----- */ + + function display_body(body, is_toplevel, output, allow_directives) { + var last = body.length - 1; + in_directive = allow_directives; + body.forEach(function(stmt, i){ + if (in_directive === true && !(stmt instanceof AST_Directive || + stmt instanceof AST_EmptyStatement || + (stmt instanceof AST_SimpleStatement && stmt.body instanceof AST_String) + )) { + in_directive = false; + } + if (!(stmt instanceof AST_EmptyStatement)) { + output.indent(); + stmt.print(output); + if (!(i == last && is_toplevel)) { + output.newline(); + if (is_toplevel) output.newline(); + } + } + if (in_directive === true && + stmt instanceof AST_SimpleStatement && + stmt.body instanceof AST_String + ) { + in_directive = false; + } + }); + in_directive = false; + }; + + AST_StatementWithBody.DEFMETHOD("_do_print_body", function(output){ + force_statement(this.body, output); + }); + + DEFPRINT(AST_Statement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + DEFPRINT(AST_Toplevel, function(self, output){ + display_body(self.body, true, output, true); + output.print(""); + }); + DEFPRINT(AST_LabeledStatement, function(self, output){ + self.label.print(output); + output.colon(); + self.body.print(output); + }); + DEFPRINT(AST_SimpleStatement, function(self, output){ + self.body.print(output); + output.semicolon(); + }); + function print_bracketed(body, output, allow_directives) { + if (body.length > 0) output.with_block(function(){ + display_body(body, false, output, allow_directives); + }); + else output.print("{}"); + }; + DEFPRINT(AST_BlockStatement, function(self, output){ + print_bracketed(self.body, output); + }); + DEFPRINT(AST_EmptyStatement, function(self, output){ + output.semicolon(); + }); + DEFPRINT(AST_Do, function(self, output){ + output.print("do"); + output.space(); + make_block(self.body, output); + output.space(); + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.semicolon(); + }); + DEFPRINT(AST_While, function(self, output){ + output.print("while"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_For, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + if (self.init) { + if (self.init instanceof AST_Definitions) { + self.init.print(output); + } else { + parenthesize_for_noin(self.init, output, true); + } + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.condition) { + self.condition.print(output); + output.print(";"); + output.space(); + } else { + output.print(";"); + } + if (self.step) { + self.step.print(output); + } + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_ForIn, function(self, output){ + output.print("for"); + output.space(); + output.with_parens(function(){ + self.init.print(output); + output.space(); + output.print("in"); + output.space(); + self.object.print(output); + }); + output.space(); + self._do_print_body(output); + }); + DEFPRINT(AST_With, function(self, output){ + output.print("with"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + self._do_print_body(output); + }); + + /* -----[ functions ]----- */ + AST_Lambda.DEFMETHOD("_do_print", function(output, nokeyword){ + var self = this; + if (!nokeyword) { + output.print("function"); + } + if (self.name) { + output.space(); + self.name.print(output); + } + output.with_parens(function(){ + self.argnames.forEach(function(arg, i){ + if (i) output.comma(); + arg.print(output); + }); + }); + output.space(); + print_bracketed(self.body, output, true); + }); + DEFPRINT(AST_Lambda, function(self, output){ + self._do_print(output); + }); + + /* -----[ exits ]----- */ + AST_Exit.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.value) { + output.space(); + this.value.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Return, function(self, output){ + self._do_print(output, "return"); + }); + DEFPRINT(AST_Throw, function(self, output){ + self._do_print(output, "throw"); + }); + + /* -----[ loop control ]----- */ + AST_LoopControl.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + if (this.label) { + output.space(); + this.label.print(output); + } + output.semicolon(); + }); + DEFPRINT(AST_Break, function(self, output){ + self._do_print(output, "break"); + }); + DEFPRINT(AST_Continue, function(self, output){ + self._do_print(output, "continue"); + }); + + /* -----[ if ]----- */ + function make_then(self, output) { + var b = self.body; + if (output.option("bracketize") + || !output.option("screw_ie8") && b instanceof AST_Do) + return make_block(b, output); + // The squeezer replaces "block"-s that contain only a single + // statement with the statement itself; technically, the AST + // is correct, but this can create problems when we output an + // IF having an ELSE clause where the THEN clause ends in an + // IF *without* an ELSE block (then the outer ELSE would refer + // to the inner IF). This function checks for this case and + // adds the block brackets if needed. + if (!b) return output.force_semicolon(); + while (true) { + if (b instanceof AST_If) { + if (!b.alternative) { + make_block(self.body, output); + return; + } + b = b.alternative; + } + else if (b instanceof AST_StatementWithBody) { + b = b.body; + } + else break; + } + force_statement(self.body, output); + }; + DEFPRINT(AST_If, function(self, output){ + output.print("if"); + output.space(); + output.with_parens(function(){ + self.condition.print(output); + }); + output.space(); + if (self.alternative) { + make_then(self, output); + output.space(); + output.print("else"); + output.space(); + if (self.alternative instanceof AST_If) + self.alternative.print(output); + else + force_statement(self.alternative, output); + } else { + self._do_print_body(output); + } + }); + + /* -----[ switch ]----- */ + DEFPRINT(AST_Switch, function(self, output){ + output.print("switch"); + output.space(); + output.with_parens(function(){ + self.expression.print(output); + }); + output.space(); + var last = self.body.length - 1; + if (last < 0) output.print("{}"); + else output.with_block(function(){ + self.body.forEach(function(branch, i){ + output.indent(true); + branch.print(output); + if (i < last && branch.body.length > 0) + output.newline(); + }); + }); + }); + AST_SwitchBranch.DEFMETHOD("_do_print_body", function(output){ + output.newline(); + this.body.forEach(function(stmt){ + output.indent(); + stmt.print(output); + output.newline(); + }); + }); + DEFPRINT(AST_Default, function(self, output){ + output.print("default:"); + self._do_print_body(output); + }); + DEFPRINT(AST_Case, function(self, output){ + output.print("case"); + output.space(); + self.expression.print(output); + output.print(":"); + self._do_print_body(output); + }); + + /* -----[ exceptions ]----- */ + DEFPRINT(AST_Try, function(self, output){ + output.print("try"); + output.space(); + print_bracketed(self.body, output); + if (self.bcatch) { + output.space(); + self.bcatch.print(output); + } + if (self.bfinally) { + output.space(); + self.bfinally.print(output); + } + }); + DEFPRINT(AST_Catch, function(self, output){ + output.print("catch"); + output.space(); + output.with_parens(function(){ + self.argname.print(output); + }); + output.space(); + print_bracketed(self.body, output); + }); + DEFPRINT(AST_Finally, function(self, output){ + output.print("finally"); + output.space(); + print_bracketed(self.body, output); + }); + + /* -----[ var/const ]----- */ + AST_Definitions.DEFMETHOD("_do_print", function(output, kind){ + output.print(kind); + output.space(); + this.definitions.forEach(function(def, i){ + if (i) output.comma(); + def.print(output); + }); + var p = output.parent(); + var in_for = p instanceof AST_For || p instanceof AST_ForIn; + var avoid_semicolon = in_for && p.init === this; + if (!avoid_semicolon) + output.semicolon(); + }); + DEFPRINT(AST_Var, function(self, output){ + self._do_print(output, "var"); + }); + DEFPRINT(AST_Const, function(self, output){ + self._do_print(output, "const"); + }); + + function parenthesize_for_noin(node, output, noin) { + if (!noin) node.print(output); + else try { + // need to take some precautions here: + // https://github.com/mishoo/UglifyJS2/issues/60 + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw output; + })); + node.print(output); + } catch(ex) { + if (ex !== output) throw ex; + node.print(output, true); + } + }; + + DEFPRINT(AST_VarDef, function(self, output){ + self.name.print(output); + if (self.value) { + output.space(); + output.print("="); + output.space(); + var p = output.parent(1); + var noin = p instanceof AST_For || p instanceof AST_ForIn; + parenthesize_for_noin(self.value, output, noin); + } + }); + + /* -----[ other expressions ]----- */ + DEFPRINT(AST_Call, function(self, output){ + self.expression.print(output); + if (self instanceof AST_New && !need_constructor_parens(self, output)) + return; + output.with_parens(function(){ + self.args.forEach(function(expr, i){ + if (i) output.comma(); + expr.print(output); + }); + }); + }); + DEFPRINT(AST_New, function(self, output){ + output.print("new"); + output.space(); + AST_Call.prototype._codegen(self, output); + }); + + AST_Seq.DEFMETHOD("_do_print", function(output){ + this.car.print(output); + if (this.cdr) { + output.comma(); + if (output.should_break()) { + output.newline(); + output.indent(); + } + this.cdr.print(output); + } + }); + DEFPRINT(AST_Seq, function(self, output){ + self._do_print(output); + // var p = output.parent(); + // if (p instanceof AST_Statement) { + // output.with_indent(output.next_indent(), function(){ + // self._do_print(output); + // }); + // } else { + // self._do_print(output); + // } + }); + DEFPRINT(AST_Dot, function(self, output){ + var expr = self.expression; + expr.print(output); + if (expr instanceof AST_Number && expr.getValue() >= 0) { + if (!/[xa-f.)]/i.test(output.last())) { + output.print("."); + } + } + output.print("."); + // the name after dot would be mapped about here. + output.add_mapping(self.end); + output.print_name(self.property); + }); + DEFPRINT(AST_Sub, function(self, output){ + self.expression.print(output); + output.print("["); + self.property.print(output); + output.print("]"); + }); + DEFPRINT(AST_UnaryPrefix, function(self, output){ + var op = self.operator; + output.print(op); + if (/^[a-z]/i.test(op) + || (/[+-]$/.test(op) + && self.expression instanceof AST_UnaryPrefix + && /^[+-]/.test(self.expression.operator))) { + output.space(); + } + self.expression.print(output); + }); + DEFPRINT(AST_UnaryPostfix, function(self, output){ + self.expression.print(output); + output.print(self.operator); + }); + DEFPRINT(AST_Binary, function(self, output){ + var op = self.operator; + self.left.print(output); + if (op[0] == ">" /* ">>" ">>>" ">" ">=" */ + && self.left instanceof AST_UnaryPostfix + && self.left.operator == "--") { + // space is mandatory to avoid outputting --> + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + output.print(op); + if ((op == "<" || op == "<<") + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "!" + && self.right.expression instanceof AST_UnaryPrefix + && self.right.expression.operator == "--") { + // space is mandatory to avoid outputting <!-- + output.print(" "); + } else { + // the space is optional depending on "beautify" + output.space(); + } + self.right.print(output); + }); + DEFPRINT(AST_Conditional, function(self, output){ + self.condition.print(output); + output.space(); + output.print("?"); + output.space(); + self.consequent.print(output); + output.space(); + output.colon(); + self.alternative.print(output); + }); + + /* -----[ literals ]----- */ + DEFPRINT(AST_Array, function(self, output){ + output.with_square(function(){ + var a = self.elements, len = a.length; + if (len > 0) output.space(); + a.forEach(function(exp, i){ + if (i) output.comma(); + exp.print(output); + // If the final element is a hole, we need to make sure it + // doesn't look like a trailing comma, by inserting an actual + // trailing comma. + if (i === len - 1 && exp instanceof AST_Hole) + output.comma(); + }); + if (len > 0) output.space(); + }); + }); + DEFPRINT(AST_Object, function(self, output){ + if (self.properties.length > 0) output.with_block(function(){ + self.properties.forEach(function(prop, i){ + if (i) { + output.print(","); + output.newline(); + } + output.indent(); + prop.print(output); + }); + output.newline(); + }); + else output.print("{}"); + }); + + function print_property_name(key, quote, output) { + if (output.option("quote_keys")) { + output.print_string(key + ""); + } else if ((typeof key == "number" + || !output.option("beautify") + && +key + "" == key) + && parseFloat(key) >= 0) { + output.print(make_num(key)); + } else if (RESERVED_WORDS(key) ? output.option("screw_ie8") : is_identifier_string(key)) { + if (quote && output.option("keep_quoted_props")) { + output.print_string(key, quote); + } else { + output.print_name(key); + } + } else { + output.print_string(key, quote); + } + } + + DEFPRINT(AST_ObjectKeyVal, function(self, output){ + print_property_name(self.key, self.quote, output); + output.colon(); + self.value.print(output); + }); + AST_ObjectProperty.DEFMETHOD("_print_getter_setter", function(type, output) { + output.print(type); + output.space(); + print_property_name(this.key.name, this.quote, output); + this.value._do_print(output, true); + }); + DEFPRINT(AST_ObjectSetter, function(self, output){ + self._print_getter_setter("set", output); + }); + DEFPRINT(AST_ObjectGetter, function(self, output){ + self._print_getter_setter("get", output); + }); + DEFPRINT(AST_Symbol, function(self, output){ + var def = self.definition(); + output.print_name(def ? def.mangled_name || def.name : self.name); + }); + DEFPRINT(AST_Hole, noop); + DEFPRINT(AST_This, function(self, output){ + output.print("this"); + }); + DEFPRINT(AST_Constant, function(self, output){ + output.print(self.getValue()); + }); + DEFPRINT(AST_String, function(self, output){ + output.print_string(self.getValue(), self.quote, in_directive); + }); + DEFPRINT(AST_Number, function(self, output){ + if (use_asm && self.start && self.start.raw != null) { + output.print(self.start.raw); + } else { + output.print(make_num(self.getValue())); + } + }); + + function regexp_safe_literal(code) { + return [ + 0x5c , // \ + 0x2f , // / + 0x2e , // . + 0x2b , // + + 0x2a , // * + 0x3f , // ? + 0x28 , // ( + 0x29 , // ) + 0x5b , // [ + 0x5d , // ] + 0x7b , // { + 0x7d , // } + 0x24 , // $ + 0x5e , // ^ + 0x3a , // : + 0x7c , // | + 0x21 , // ! + 0x0a , // \n + 0x0d , // \r + 0x00 , // \0 + 0xfeff , // Unicode BOM + 0x2028 , // unicode "line separator" + 0x2029 , // unicode "paragraph separator" + ].indexOf(code) < 0; + }; + + DEFPRINT(AST_RegExp, function(self, output){ + var str = self.getValue().toString(); + if (output.option("ascii_only")) { + str = output.to_ascii(str); + } else if (output.option("unescape_regexps")) { + str = str.split("\\\\").map(function(str){ + return str.replace(/\\u[0-9a-fA-F]{4}|\\x[0-9a-fA-F]{2}/g, function(s){ + var code = parseInt(s.substr(2), 16); + return regexp_safe_literal(code) ? String.fromCharCode(code) : s; + }); + }).join("\\\\"); + } + output.print(str); + var p = output.parent(); + if (p instanceof AST_Binary && /^in/.test(p.operator) && p.left === self) + output.print(" "); + }); + + function force_statement(stat, output) { + if (output.option("bracketize")) { + make_block(stat, output); + } else { + if (!stat || stat instanceof AST_EmptyStatement) + output.force_semicolon(); + else + stat.print(output); + } + }; + + // self should be AST_New. decide if we want to show parens or not. + function need_constructor_parens(self, output) { + // Always print parentheses with arguments + if (self.args.length > 0) return true; + + return output.option("beautify"); + }; + + function best_of(a) { + var best = a[0], len = best.length; + for (var i = 1; i < a.length; ++i) { + if (a[i].length < len) { + best = a[i]; + len = best.length; + } + } + return best; + }; + + function make_num(num) { + var str = num.toString(10), a = [ str.replace(/^0\./, ".").replace('e+', 'e') ], m; + if (Math.floor(num) === num) { + if (num >= 0) { + a.push("0x" + num.toString(16).toLowerCase(), // probably pointless + "0" + num.toString(8)); // same. + } else { + a.push("-0x" + (-num).toString(16).toLowerCase(), // probably pointless + "-0" + (-num).toString(8)); // same. + } + if ((m = /^(.*?)(0+)$/.exec(num))) { + a.push(m[1] + "e" + m[2].length); + } + } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { + a.push(m[2] + "e-" + (m[1].length + m[2].length), + str.substr(str.indexOf("."))); + } + return best_of(a); + }; + + function make_block(stmt, output) { + if (!stmt || stmt instanceof AST_EmptyStatement) + output.print("{}"); + else if (stmt instanceof AST_BlockStatement) + stmt.print(output); + else output.with_block(function(){ + output.indent(); + stmt.print(output); + output.newline(); + }); + }; + + /* -----[ source map generators ]----- */ + + function DEFMAP(nodetype, generator) { + nodetype.DEFMETHOD("add_source_map", function(stream){ + generator(this, stream); + }); + }; + + // We could easily add info for ALL nodes, but it seems to me that + // would be quite wasteful, hence this noop in the base class. + DEFMAP(AST_Node, noop); + + function basic_sourcemap_gen(self, output) { + output.add_mapping(self.start); + }; + + // XXX: I'm not exactly sure if we need it for all of these nodes, + // or if we should add even more. + + DEFMAP(AST_Directive, basic_sourcemap_gen); + DEFMAP(AST_Debugger, basic_sourcemap_gen); + DEFMAP(AST_Symbol, basic_sourcemap_gen); + DEFMAP(AST_Jump, basic_sourcemap_gen); + DEFMAP(AST_StatementWithBody, basic_sourcemap_gen); + DEFMAP(AST_LabeledStatement, noop); // since the label symbol will mark it + DEFMAP(AST_Lambda, basic_sourcemap_gen); + DEFMAP(AST_Switch, basic_sourcemap_gen); + DEFMAP(AST_SwitchBranch, basic_sourcemap_gen); + DEFMAP(AST_BlockStatement, basic_sourcemap_gen); + DEFMAP(AST_Toplevel, noop); + DEFMAP(AST_New, basic_sourcemap_gen); + DEFMAP(AST_Try, basic_sourcemap_gen); + DEFMAP(AST_Catch, basic_sourcemap_gen); + DEFMAP(AST_Finally, basic_sourcemap_gen); + DEFMAP(AST_Definitions, basic_sourcemap_gen); + DEFMAP(AST_Constant, basic_sourcemap_gen); + DEFMAP(AST_ObjectSetter, function(self, output){ + output.add_mapping(self.start, self.key.name); + }); + DEFMAP(AST_ObjectGetter, function(self, output){ + output.add_mapping(self.start, self.key.name); + }); + DEFMAP(AST_ObjectProperty, function(self, output){ + output.add_mapping(self.start, self.key); + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function Compressor(options, false_by_default) { + if (!(this instanceof Compressor)) + return new Compressor(options, false_by_default); + TreeTransformer.call(this, this.before, this.after); + this.options = defaults(options, { + angular : false, + booleans : !false_by_default, + cascade : !false_by_default, + collapse_vars : !false_by_default, + comparisons : !false_by_default, + conditionals : !false_by_default, + dead_code : !false_by_default, + drop_console : false, + drop_debugger : !false_by_default, + evaluate : !false_by_default, + expression : false, + global_defs : {}, + hoist_funs : !false_by_default, + hoist_vars : false, + if_return : !false_by_default, + join_vars : !false_by_default, + keep_fargs : true, + keep_fnames : false, + keep_infinity : false, + loops : !false_by_default, + negate_iife : !false_by_default, + passes : 1, + properties : !false_by_default, + pure_getters : !false_by_default && "strict", + pure_funcs : null, + reduce_vars : !false_by_default, + screw_ie8 : true, + sequences : !false_by_default, + side_effects : !false_by_default, + switches : !false_by_default, + top_retain : null, + toplevel : !!(options && options["top_retain"]), + unsafe : false, + unsafe_comps : false, + unsafe_math : false, + unsafe_proto : false, + unsafe_regexp : false, + unused : !false_by_default, + warnings : true, + }, true); + var pure_funcs = this.options["pure_funcs"]; + if (typeof pure_funcs == "function") { + this.pure_funcs = pure_funcs; + } else { + this.pure_funcs = pure_funcs ? function(node) { + return pure_funcs.indexOf(node.expression.print_to_string()) < 0; + } : return_true; + } + var top_retain = this.options["top_retain"]; + if (top_retain instanceof RegExp) { + this.top_retain = function(def) { + return top_retain.test(def.name); + }; + } else if (typeof top_retain == "function") { + this.top_retain = top_retain; + } else if (top_retain) { + if (typeof top_retain == "string") { + top_retain = top_retain.split(/,/); + } + this.top_retain = function(def) { + return top_retain.indexOf(def.name) >= 0; + }; + } + var sequences = this.options["sequences"]; + this.sequences_limit = sequences == 1 ? 200 : sequences | 0; + this.warnings_produced = {}; +}; + +Compressor.prototype = new TreeTransformer; +merge(Compressor.prototype, { + option: function(key) { return this.options[key] }, + compress: function(node) { + if (this.option("expression")) { + node = node.process_expression(true); + } + var passes = +this.options.passes || 1; + for (var pass = 0; pass < passes && pass < 3; ++pass) { + if (pass > 0 || this.option("reduce_vars")) + node.reset_opt_flags(this, true); + node = node.transform(this); + } + if (this.option("expression")) { + node = node.process_expression(false); + } + return node; + }, + info: function() { + if (this.options.warnings == "verbose") { + AST_Node.warn.apply(AST_Node, arguments); + } + }, + warn: function(text, props) { + if (this.options.warnings) { + // only emit unique warnings + var message = string_template(text, props); + if (!(message in this.warnings_produced)) { + this.warnings_produced[message] = true; + AST_Node.warn.apply(AST_Node, arguments); + } + } + }, + clear_warnings: function() { + this.warnings_produced = {}; + }, + before: function(node, descend, in_list) { + if (node._squeezed) return node; + var was_scope = false; + if (node instanceof AST_Scope) { + node = node.hoist_declarations(this); + was_scope = true; + } + // Before https://github.com/mishoo/UglifyJS2/pull/1602 AST_Node.optimize() + // would call AST_Node.transform() if a different instance of AST_Node is + // produced after OPT(). + // This corrupts TreeWalker.stack, which cause AST look-ups to malfunction. + // Migrate and defer all children's AST_Node.transform() to below, which + // will now happen after this parent AST_Node has been properly substituted + // thus gives a consistent AST snapshot. + descend(node, this); + // Existing code relies on how AST_Node.optimize() worked, and omitting the + // following replacement call would result in degraded efficiency of both + // output and performance. + descend(node, this); + var opt = node.optimize(this); + if (was_scope && opt instanceof AST_Scope) { + opt.drop_unused(this); + descend(opt, this); + } + if (opt === node) opt._squeezed = true; + return opt; + } +}); + +(function(){ + + function OPT(node, optimizer) { + node.DEFMETHOD("optimize", function(compressor){ + var self = this; + if (self._optimized) return self; + if (compressor.has_directive("use asm")) return self; + var opt = optimizer(self, compressor); + opt._optimized = true; + return opt; + }); + }; + + OPT(AST_Node, function(self, compressor){ + return self; + }); + + AST_Node.DEFMETHOD("equivalent_to", function(node){ + return this.TYPE == node.TYPE && this.print_to_string() == node.print_to_string(); + }); + + AST_Node.DEFMETHOD("process_expression", function(insert, compressor) { + var self = this; + var tt = new TreeTransformer(function(node) { + if (insert && node instanceof AST_SimpleStatement) { + return make_node(AST_Return, node, { + value: node.body + }); + } + if (!insert && node instanceof AST_Return) { + if (compressor) { + var value = node.value && node.value.drop_side_effect_free(compressor, true); + return value ? make_node(AST_SimpleStatement, node, { + body: value + }) : make_node(AST_EmptyStatement, node); + } + return make_node(AST_SimpleStatement, node, { + body: node.value || make_node(AST_UnaryPrefix, node, { + operator: "void", + expression: make_node(AST_Number, node, { + value: 0 + }) + }) + }); + } + if (node instanceof AST_Lambda && node !== self) { + return node; + } + if (node instanceof AST_Block) { + var index = node.body.length - 1; + if (index >= 0) { + node.body[index] = node.body[index].transform(tt); + } + } + if (node instanceof AST_If) { + node.body = node.body.transform(tt); + if (node.alternative) { + node.alternative = node.alternative.transform(tt); + } + } + if (node instanceof AST_With) { + node.body = node.body.transform(tt); + } + return node; + }); + return self.transform(tt); + }); + + AST_Node.DEFMETHOD("reset_opt_flags", function(compressor, rescan){ + var reduce_vars = rescan && compressor.option("reduce_vars"); + var toplevel = compressor.option("toplevel"); + var safe_ids = Object.create(null); + var suppressor = new TreeWalker(function(node) { + if (node instanceof AST_Symbol) { + var d = node.definition(); + if (node instanceof AST_SymbolRef) d.references.push(node); + d.fixed = false; + } + }); + var tw = new TreeWalker(function(node, descend){ + node._squeezed = false; + node._optimized = false; + if (reduce_vars) { + if (node instanceof AST_Toplevel) node.globals.each(reset_def); + if (node instanceof AST_Scope) node.variables.each(reset_def); + if (node instanceof AST_SymbolRef) { + var d = node.definition(); + d.references.push(node); + if (d.fixed === undefined || !is_safe(d) + || is_modified(node, 0, node.fixed_value() instanceof AST_Lambda)) { + d.fixed = false; + } else { + var parent = tw.parent(); + if (parent instanceof AST_Assign && parent.operator == "=" && node === parent.right + || parent instanceof AST_Call && node !== parent.expression + || parent instanceof AST_Return && node === parent.value && node.scope !== d.scope + || parent instanceof AST_VarDef && node === parent.value) { + d.escaped = true; + } + } + } + if (node instanceof AST_SymbolCatch) { + node.definition().fixed = false; + } + if (node instanceof AST_VarDef) { + var d = node.name.definition(); + if (d.fixed == null) { + if (node.value) { + d.fixed = function() { + return node.value; + }; + mark(d, false); + descend(); + } else { + d.fixed = null; + } + mark(d, true); + return true; + } else if (node.value) { + d.fixed = false; + } + } + if (node instanceof AST_Defun) { + var d = node.name.definition(); + if (!toplevel && d.global || is_safe(d)) { + d.fixed = false; + } else { + d.fixed = node; + mark(d, true); + } + var save_ids = safe_ids; + safe_ids = Object.create(null); + descend(); + safe_ids = save_ids; + return true; + } + if (node instanceof AST_Function) { + push(); + var iife; + if (!node.name + && (iife = tw.parent()) instanceof AST_Call + && iife.expression === node) { + // Virtually turn IIFE parameters into variable definitions: + // (function(a,b) {...})(c,d) => (function() {var a=c,b=d; ...})() + // So existing transformation rules can work on them. + node.argnames.forEach(function(arg, i) { + var d = arg.definition(); + if (!node.uses_arguments && d.fixed === undefined) { + d.fixed = function() { + return iife.args[i] || make_node(AST_Undefined, iife); + }; + mark(d, true); + } else { + d.fixed = false; + } + }); + } + descend(); + pop(); + return true; + } + if (node instanceof AST_Accessor) { + var save_ids = safe_ids; + safe_ids = Object.create(null); + descend(); + safe_ids = save_ids; + return true; + } + if (node instanceof AST_Binary + && (node.operator == "&&" || node.operator == "||")) { + node.left.walk(tw); + push(); + node.right.walk(tw); + pop(); + return true; + } + if (node instanceof AST_Conditional) { + node.condition.walk(tw); + push(); + node.consequent.walk(tw); + pop(); + push(); + node.alternative.walk(tw); + pop(); + return true; + } + if (node instanceof AST_If || node instanceof AST_DWLoop) { + node.condition.walk(tw); + push(); + node.body.walk(tw); + pop(); + if (node.alternative) { + push(); + node.alternative.walk(tw); + pop(); + } + return true; + } + if (node instanceof AST_LabeledStatement) { + push(); + node.body.walk(tw); + pop(); + return true; + } + if (node instanceof AST_For) { + if (node.init) node.init.walk(tw); + push(); + if (node.condition) node.condition.walk(tw); + node.body.walk(tw); + if (node.step) node.step.walk(tw); + pop(); + return true; + } + if (node instanceof AST_ForIn) { + node.init.walk(suppressor); + node.object.walk(tw); + push(); + node.body.walk(tw); + pop(); + return true; + } + if (node instanceof AST_Try) { + push(); + walk_body(node, tw); + pop(); + if (node.bcatch) { + push(); + node.bcatch.walk(tw); + pop(); + } + if (node.bfinally) node.bfinally.walk(tw); + return true; + } + if (node instanceof AST_SwitchBranch) { + push(); + descend(); + pop(); + return true; + } + } + }); + this.walk(tw); + + function mark(def, safe) { + safe_ids[def.id] = safe; + } + + function is_safe(def) { + if (safe_ids[def.id]) { + if (def.fixed == null) { + var orig = def.orig[0]; + if (orig instanceof AST_SymbolFunarg || orig.name == "arguments") return false; + def.fixed = make_node(AST_Undefined, orig); + } + return true; + } + } + + function push() { + safe_ids = Object.create(safe_ids); + } + + function pop() { + safe_ids = Object.getPrototypeOf(safe_ids); + } + + function reset_def(def) { + def.escaped = false; + if (def.scope.uses_eval) { + def.fixed = false; + } else if (toplevel || !def.global || def.orig[0] instanceof AST_SymbolConst) { + def.fixed = undefined; + } else { + def.fixed = false; + } + def.references = []; + def.should_replace = undefined; + } + + function is_modified(node, level, func) { + var parent = tw.parent(level); + if (is_lhs(node, parent) + || !func && parent instanceof AST_Call && parent.expression === node) { + return true; + } else if (parent instanceof AST_PropAccess && parent.expression === node) { + return !func && is_modified(parent, level + 1); + } + } + }); + + AST_SymbolRef.DEFMETHOD("fixed_value", function() { + var fixed = this.definition().fixed; + if (!fixed || fixed instanceof AST_Node) return fixed; + return fixed(); + }); + + function is_reference_const(ref) { + if (!(ref instanceof AST_SymbolRef)) return false; + var orig = ref.definition().orig; + for (var i = orig.length; --i >= 0;) { + if (orig[i] instanceof AST_SymbolConst) return true; + } + } + + function find_variable(compressor, name) { + var scope, i = 0; + while (scope = compressor.parent(i++)) { + if (scope instanceof AST_Scope) break; + if (scope instanceof AST_Catch) { + scope = scope.argname.definition().scope; + break; + } + } + return scope.find_variable(name); + } + + function make_node(ctor, orig, props) { + if (!props) props = {}; + if (orig) { + if (!props.start) props.start = orig.start; + if (!props.end) props.end = orig.end; + } + return new ctor(props); + }; + + function make_node_from_constant(val, orig) { + switch (typeof val) { + case "string": + return make_node(AST_String, orig, { + value: val + }); + case "number": + if (isNaN(val)) return make_node(AST_NaN, orig); + if (isFinite(val)) { + return 1 / val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Number, orig, { value: -val }) + }) : make_node(AST_Number, orig, { value: val }); + } + return val < 0 ? make_node(AST_UnaryPrefix, orig, { + operator: "-", + expression: make_node(AST_Infinity, orig) + }) : make_node(AST_Infinity, orig); + case "boolean": + return make_node(val ? AST_True : AST_False, orig); + case "undefined": + return make_node(AST_Undefined, orig); + default: + if (val === null) { + return make_node(AST_Null, orig, { value: null }); + } + if (val instanceof RegExp) { + return make_node(AST_RegExp, orig, { value: val }); + } + throw new Error(string_template("Can't handle constant of type: {type}", { + type: typeof val + })); + } + }; + + // we shouldn't compress (1,func)(something) to + // func(something) because that changes the meaning of + // the func (becomes lexical instead of global). + function maintain_this_binding(parent, orig, val) { + if (parent instanceof AST_UnaryPrefix && parent.operator == "delete" + || parent instanceof AST_Call && parent.expression === orig + && (val instanceof AST_PropAccess || val instanceof AST_SymbolRef && val.name == "eval")) { + return make_node(AST_Seq, orig, { + car: make_node(AST_Number, orig, { + value: 0 + }), + cdr: val + }); + } + return val; + } + + function as_statement_array(thing) { + if (thing === null) return []; + if (thing instanceof AST_BlockStatement) return thing.body; + if (thing instanceof AST_EmptyStatement) return []; + if (thing instanceof AST_Statement) return [ thing ]; + throw new Error("Can't convert thing to statement array"); + }; + + function is_empty(thing) { + if (thing === null) return true; + if (thing instanceof AST_EmptyStatement) return true; + if (thing instanceof AST_BlockStatement) return thing.body.length == 0; + return false; + }; + + function loop_body(x) { + if (x instanceof AST_Switch) return x; + if (x instanceof AST_For || x instanceof AST_ForIn || x instanceof AST_DWLoop) { + return (x.body instanceof AST_BlockStatement ? x.body : x); + } + return x; + }; + + function is_iife_call(node) { + if (node instanceof AST_Call && !(node instanceof AST_New)) { + return node.expression instanceof AST_Function || is_iife_call(node.expression); + } + return false; + } + + function tighten_body(statements, compressor) { + var CHANGED, max_iter = 10; + do { + CHANGED = false; + if (compressor.option("angular")) { + statements = process_for_angular(statements); + } + statements = eliminate_spurious_blocks(statements); + if (compressor.option("dead_code")) { + statements = eliminate_dead_code(statements, compressor); + } + if (compressor.option("if_return")) { + statements = handle_if_return(statements, compressor); + } + if (compressor.sequences_limit > 0) { + statements = sequencesize(statements, compressor); + } + if (compressor.option("join_vars")) { + statements = join_consecutive_vars(statements, compressor); + } + if (compressor.option("collapse_vars")) { + statements = collapse_single_use_vars(statements, compressor); + } + } while (CHANGED && max_iter-- > 0); + + return statements; + + function collapse_single_use_vars(statements, compressor) { + // Iterate statements backwards looking for a statement with a var/const + // declaration immediately preceding it. Grab the rightmost var definition + // and if it has exactly one reference then attempt to replace its reference + // in the statement with the var value and then erase the var definition. + + var self = compressor.self(); + var var_defs_removed = false; + var toplevel = compressor.option("toplevel"); + for (var stat_index = statements.length; --stat_index >= 0;) { + var stat = statements[stat_index]; + if (stat instanceof AST_Definitions) continue; + + // Process child blocks of statement if present. + [stat, stat.body, stat.alternative, stat.bcatch, stat.bfinally].forEach(function(node) { + node && node.body && collapse_single_use_vars(node.body, compressor); + }); + + // The variable definition must precede a statement. + if (stat_index <= 0) break; + var prev_stat_index = stat_index - 1; + var prev_stat = statements[prev_stat_index]; + if (!(prev_stat instanceof AST_Definitions)) continue; + var var_defs = prev_stat.definitions; + if (var_defs == null) continue; + + var var_names_seen = {}; + var side_effects_encountered = false; + var lvalues_encountered = false; + var lvalues = {}; + + // Scan variable definitions from right to left. + for (var var_defs_index = var_defs.length; --var_defs_index >= 0;) { + + // Obtain var declaration and var name with basic sanity check. + var var_decl = var_defs[var_defs_index]; + if (var_decl.value == null) break; + var var_name = var_decl.name.name; + if (!var_name || !var_name.length) break; + + // Bail if we've seen a var definition of same name before. + if (var_name in var_names_seen) break; + var_names_seen[var_name] = true; + + // Only interested in cases with just one reference to the variable. + var def = self.find_variable && self.find_variable(var_name); + if (!def || !def.references || def.references.length !== 1 + || var_name == "arguments" || (!toplevel && def.global)) { + side_effects_encountered = true; + continue; + } + var ref = def.references[0]; + + // Don't replace ref if eval() or with statement in scope. + if (ref.scope.uses_eval || ref.scope.uses_with) break; + + // Constant single use vars can be replaced in any scope. + if (var_decl.value.is_constant()) { + var ctt = new TreeTransformer(function(node) { + var parent = ctt.parent(); + if (parent instanceof AST_IterationStatement + && (parent.condition === node || parent.init === node)) { + return node; + } + if (node === ref) + return replace_var(node, parent, true); + }); + stat.transform(ctt); + continue; + } + + // Restrict var replacement to constants if side effects encountered. + if (side_effects_encountered |= lvalues_encountered) continue; + + var value_has_side_effects = var_decl.value.has_side_effects(compressor); + // Non-constant single use vars can only be replaced in same scope. + if (ref.scope !== self) { + side_effects_encountered |= value_has_side_effects; + continue; + } + + // Detect lvalues in var value. + var tw = new TreeWalker(function(node){ + if (node instanceof AST_SymbolRef && is_lvalue(node, tw.parent())) { + lvalues[node.name] = lvalues_encountered = true; + } + }); + var_decl.value.walk(tw); + + // Replace the non-constant single use var in statement if side effect free. + var unwind = false; + var tt = new TreeTransformer( + function preorder(node) { + if (unwind) return node; + var parent = tt.parent(); + if (node instanceof AST_Lambda + || node instanceof AST_Try + || node instanceof AST_With + || node instanceof AST_Case + || node instanceof AST_IterationStatement + || (parent instanceof AST_If && node !== parent.condition) + || (parent instanceof AST_Conditional && node !== parent.condition) + || (node instanceof AST_SymbolRef + && value_has_side_effects + && !are_references_in_scope(node.definition(), self)) + || (parent instanceof AST_Binary + && (parent.operator == "&&" || parent.operator == "||") + && node === parent.right) + || (parent instanceof AST_Switch && node !== parent.expression)) { + return side_effects_encountered = unwind = true, node; + } + function are_references_in_scope(def, scope) { + if (def.orig.length === 1 + && def.orig[0] instanceof AST_SymbolDefun) return true; + if (def.scope !== scope) return false; + var refs = def.references; + for (var i = 0, len = refs.length; i < len; i++) { + if (refs[i].scope !== scope) return false; + } + return true; + } + }, + function postorder(node) { + if (unwind) return node; + if (node === ref) + return unwind = true, replace_var(node, tt.parent(), false); + if (side_effects_encountered |= node.has_side_effects(compressor)) + return unwind = true, node; + if (lvalues_encountered && node instanceof AST_SymbolRef && node.name in lvalues) { + side_effects_encountered = true; + return unwind = true, node; + } + } + ); + stat.transform(tt); + } + } + + // Remove extraneous empty statments in block after removing var definitions. + // Leave at least one statement in `statements`. + if (var_defs_removed) for (var i = statements.length; --i >= 0;) { + if (statements.length > 1 && statements[i] instanceof AST_EmptyStatement) + statements.splice(i, 1); + } + + return statements; + + function is_lvalue(node, parent) { + return node instanceof AST_SymbolRef && is_lhs(node, parent); + } + function replace_var(node, parent, is_constant) { + if (is_lvalue(node, parent)) return node; + + // Remove var definition and return its value to the TreeTransformer to replace. + var value = maintain_this_binding(parent, node, var_decl.value); + var_decl.value = null; + + var_defs.splice(var_defs_index, 1); + if (var_defs.length === 0) { + statements[prev_stat_index] = make_node(AST_EmptyStatement, self); + var_defs_removed = true; + } + // Further optimize statement after substitution. + stat.reset_opt_flags(compressor); + + compressor.info("Collapsing " + (is_constant ? "constant" : "variable") + + " " + var_name + " [{file}:{line},{col}]", node.start); + CHANGED = true; + return value; + } + } + + function process_for_angular(statements) { + function has_inject(comment) { + return /@ngInject/.test(comment.value); + } + function make_arguments_names_list(func) { + return func.argnames.map(function(sym){ + return make_node(AST_String, sym, { value: sym.name }); + }); + } + function make_array(orig, elements) { + return make_node(AST_Array, orig, { elements: elements }); + } + function make_injector(func, name) { + return make_node(AST_SimpleStatement, func, { + body: make_node(AST_Assign, func, { + operator: "=", + left: make_node(AST_Dot, name, { + expression: make_node(AST_SymbolRef, name, name), + property: "$inject" + }), + right: make_array(func, make_arguments_names_list(func)) + }) + }); + } + function check_expression(body) { + if (body && body.args) { + // if this is a function call check all of arguments passed + body.args.forEach(function(argument, index, array) { + var comments = argument.start.comments_before; + // if the argument is function preceded by @ngInject + if (argument instanceof AST_Lambda && comments.length && has_inject(comments[0])) { + // replace the function with an array of names of its parameters and function at the end + array[index] = make_array(argument, make_arguments_names_list(argument).concat(argument)); + } + }); + // if this is chained call check previous one recursively + if (body.expression && body.expression.expression) { + check_expression(body.expression.expression); + } + } + } + return statements.reduce(function(a, stat){ + a.push(stat); + + if (stat.body && stat.body.args) { + check_expression(stat.body); + } else { + var token = stat.start; + var comments = token.comments_before; + if (comments && comments.length > 0) { + var last = comments.pop(); + if (has_inject(last)) { + // case 1: defun + if (stat instanceof AST_Defun) { + a.push(make_injector(stat, stat.name)); + } + else if (stat instanceof AST_Definitions) { + stat.definitions.forEach(function(def) { + if (def.value && def.value instanceof AST_Lambda) { + a.push(make_injector(def.value, def.name)); + } + }); + } + else { + compressor.warn("Unknown statement marked with @ngInject [{file}:{line},{col}]", token); + } + } + } + } + + return a; + }, []); + } + + function eliminate_spurious_blocks(statements) { + var seen_dirs = []; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_BlockStatement) { + CHANGED = true; + a.push.apply(a, eliminate_spurious_blocks(stat.body)); + } else if (stat instanceof AST_EmptyStatement) { + CHANGED = true; + } else if (stat instanceof AST_Directive) { + if (seen_dirs.indexOf(stat.value) < 0) { + a.push(stat); + seen_dirs.push(stat.value); + } else { + CHANGED = true; + } + } else { + a.push(stat); + } + return a; + }, []); + }; + + function handle_if_return(statements, compressor) { + var self = compressor.self(); + var multiple_if_returns = has_multiple_if_returns(statements); + var in_lambda = self instanceof AST_Lambda; + var ret = []; // Optimized statements, build from tail to front + loop: for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + switch (true) { + case (in_lambda && stat instanceof AST_Return && !stat.value && ret.length == 0): + CHANGED = true; + // note, ret.length is probably always zero + // because we drop unreachable code before this + // step. nevertheless, it's good to check. + continue loop; + case stat instanceof AST_If: + if (stat.body instanceof AST_Return) { + //--- + // pretty silly case, but: + // if (foo()) return; return; ==> foo(); return; + if (((in_lambda && ret.length == 0) + || (ret[0] instanceof AST_Return && !ret[0].value)) + && !stat.body.value && !stat.alternative) { + CHANGED = true; + var cond = make_node(AST_SimpleStatement, stat.condition, { + body: stat.condition + }); + ret.unshift(cond); + continue loop; + } + //--- + // if (foo()) return x; return y; ==> return foo() ? x : y; + if (ret[0] instanceof AST_Return && stat.body.value && ret[0].value && !stat.alternative) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0]; + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return x; [ return ; ] ==> return foo() ? x : undefined; + if (multiple_if_returns && (ret.length == 0 || ret[0] instanceof AST_Return) + && stat.body.value && !stat.alternative && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.alternative = ret[0] || make_node(AST_Return, stat, { + value: null + }); + ret[0] = stat.transform(compressor); + continue loop; + } + //--- + // if (foo()) return; [ else x... ]; y... ==> if (!foo()) { x...; y... } + if (!stat.body.value && in_lambda) { + CHANGED = true; + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + var body = as_statement_array(stat.alternative).concat(ret); + var funs = extract_functions_from_statement_array(body); + stat.body = make_node(AST_BlockStatement, stat, { + body: body + }); + stat.alternative = null; + ret = funs.concat([ stat.transform(compressor) ]); + continue loop; + } + + //--- + // if (a) return b; if (c) return d; e; ==> return a ? b : c ? d : void e; + // + // if sequences is not enabled, this can lead to an endless loop (issue #866). + // however, with sequences on this helps producing slightly better output for + // the example code. + if (compressor.option("sequences") + && i > 0 && statements[i - 1] instanceof AST_If && statements[i - 1].body instanceof AST_Return + && ret.length == 1 && in_lambda && ret[0] instanceof AST_SimpleStatement + && !stat.alternative) { + CHANGED = true; + ret.push(make_node(AST_Return, ret[0], { + value: null + }).transform(compressor)); + ret.unshift(stat); + continue loop; + } + } + + var ab = aborts(stat.body); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + var body = as_statement_array(stat.body).slice(0, -1); + stat = stat.clone(); + stat.condition = stat.condition.negate(compressor); + stat.body = make_node(AST_BlockStatement, stat, { + body: as_statement_array(stat.alternative).concat(ret) + }); + stat.alternative = make_node(AST_BlockStatement, stat, { + body: body + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + var ab = aborts(stat.alternative); + var lct = ab instanceof AST_LoopControl ? compressor.loopcontrol_target(ab) : null; + if (ab && ((ab instanceof AST_Return && !ab.value && in_lambda) + || (ab instanceof AST_Continue && self === loop_body(lct)) + || (ab instanceof AST_Break && lct instanceof AST_BlockStatement && self === lct))) { + if (ab.label) { + remove(ab.label.thedef.references, ab); + } + CHANGED = true; + stat = stat.clone(); + stat.body = make_node(AST_BlockStatement, stat.body, { + body: as_statement_array(stat.body).concat(ret) + }); + stat.alternative = make_node(AST_BlockStatement, stat.alternative, { + body: as_statement_array(stat.alternative).slice(0, -1) + }); + ret = [ stat.transform(compressor) ]; + continue loop; + } + + ret.unshift(stat); + break; + default: + ret.unshift(stat); + break; + } + } + return ret; + + function has_multiple_if_returns(statements) { + var n = 0; + for (var i = statements.length; --i >= 0;) { + var stat = statements[i]; + if (stat instanceof AST_If && stat.body instanceof AST_Return) { + if (++n > 1) return true; + } + } + return false; + } + }; + + function eliminate_dead_code(statements, compressor) { + var has_quit = false; + var orig = statements.length; + var self = compressor.self(); + statements = statements.reduce(function(a, stat){ + if (has_quit) { + extract_declarations_from_unreachable_code(compressor, stat, a); + } else { + if (stat instanceof AST_LoopControl) { + var lct = compressor.loopcontrol_target(stat); + if ((stat instanceof AST_Break + && !(lct instanceof AST_IterationStatement) + && loop_body(lct) === self) || (stat instanceof AST_Continue + && loop_body(lct) === self)) { + if (stat.label) { + remove(stat.label.thedef.references, stat); + } + } else { + a.push(stat); + } + } else { + a.push(stat); + } + if (aborts(stat)) has_quit = true; + } + return a; + }, []); + CHANGED = statements.length != orig; + return statements; + }; + + function sequencesize(statements, compressor) { + if (statements.length < 2) return statements; + var seq = [], ret = []; + function push_seq() { + seq = AST_Seq.from_array(seq); + if (seq) ret.push(make_node(AST_SimpleStatement, seq, { + body: seq + })); + seq = []; + }; + statements.forEach(function(stat){ + if (stat instanceof AST_SimpleStatement) { + if (seqLength(seq) >= compressor.sequences_limit) push_seq(); + var body = stat.body; + if (seq.length > 0) body = body.drop_side_effect_free(compressor); + if (body) seq.push(body); + } else { + push_seq(); + ret.push(stat); + } + }); + push_seq(); + ret = sequencesize_2(ret, compressor); + CHANGED = ret.length != statements.length; + return ret; + }; + + function seqLength(a) { + for (var len = 0, i = 0; i < a.length; ++i) { + var stat = a[i]; + if (stat instanceof AST_Seq) { + len += stat.len(); + } else { + len++; + } + } + return len; + }; + + function sequencesize_2(statements, compressor) { + function cons_seq(right) { + ret.pop(); + var left = prev.body; + if (left instanceof AST_Seq) { + left.add(right); + } else { + left = AST_Seq.cons(left, right); + } + return left.transform(compressor); + }; + var ret = [], prev = null; + statements.forEach(function(stat){ + if (prev) { + if (stat instanceof AST_For) { + var opera = {}; + try { + prev.body.walk(new TreeWalker(function(node){ + if (node instanceof AST_Binary && node.operator == "in") + throw opera; + })); + if (stat.init && !(stat.init instanceof AST_Definitions)) { + stat.init = cons_seq(stat.init); + } + else if (!stat.init) { + stat.init = prev.body.drop_side_effect_free(compressor); + ret.pop(); + } + } catch(ex) { + if (ex !== opera) throw ex; + } + } + else if (stat instanceof AST_If) { + stat.condition = cons_seq(stat.condition); + } + else if (stat instanceof AST_With) { + stat.expression = cons_seq(stat.expression); + } + else if (stat instanceof AST_Exit && stat.value) { + stat.value = cons_seq(stat.value); + } + else if (stat instanceof AST_Exit) { + stat.value = cons_seq(make_node(AST_Undefined, stat).transform(compressor)); + } + else if (stat instanceof AST_Switch) { + stat.expression = cons_seq(stat.expression); + } + } + ret.push(stat); + prev = stat instanceof AST_SimpleStatement ? stat : null; + }); + return ret; + }; + + function join_consecutive_vars(statements, compressor) { + var prev = null; + return statements.reduce(function(a, stat){ + if (stat instanceof AST_Definitions && prev && prev.TYPE == stat.TYPE) { + prev.definitions = prev.definitions.concat(stat.definitions); + CHANGED = true; + } + else if (stat instanceof AST_For + && prev instanceof AST_Var + && (!stat.init || stat.init.TYPE == prev.TYPE)) { + CHANGED = true; + a.pop(); + if (stat.init) { + stat.init.definitions = prev.definitions.concat(stat.init.definitions); + } else { + stat.init = prev; + } + a.push(stat); + prev = stat; + } + else { + prev = stat; + a.push(stat); + } + return a; + }, []); + }; + + }; + + function extract_functions_from_statement_array(statements) { + var funs = []; + for (var i = statements.length - 1; i >= 0; --i) { + var stat = statements[i]; + if (stat instanceof AST_Defun) { + statements.splice(i, 1); + funs.unshift(stat); + } + } + return funs; + } + + function extract_declarations_from_unreachable_code(compressor, stat, target) { + if (!(stat instanceof AST_Defun)) { + compressor.warn("Dropping unreachable code [{file}:{line},{col}]", stat.start); + } + stat.walk(new TreeWalker(function(node){ + if (node instanceof AST_Definitions) { + compressor.warn("Declarations in unreachable code! [{file}:{line},{col}]", node.start); + node.remove_initializers(); + target.push(node); + return true; + } + if (node instanceof AST_Defun) { + target.push(node); + return true; + } + if (node instanceof AST_Scope) { + return true; + } + })); + }; + + function is_undefined(node, compressor) { + return node.is_undefined + || node instanceof AST_Undefined + || node instanceof AST_UnaryPrefix + && node.operator == "void" + && !node.expression.has_side_effects(compressor); + } + + // may_throw_on_access() + // returns true if this node may be null, undefined or contain `AST_Accessor` + (function(def) { + AST_Node.DEFMETHOD("may_throw_on_access", function(compressor) { + var pure_getters = compressor.option("pure_getters"); + return !pure_getters || this._throw_on_access(pure_getters); + }); + + function is_strict(pure_getters) { + return /strict/.test(pure_getters); + } + + def(AST_Node, is_strict); + def(AST_Null, return_true); + def(AST_Undefined, return_true); + def(AST_Constant, return_false); + def(AST_Array, return_false); + def(AST_Object, function(pure_getters) { + if (!is_strict(pure_getters)) return false; + for (var i = this.properties.length; --i >=0;) + if (this.properties[i].value instanceof AST_Accessor) return true; + return false; + }); + def(AST_Function, return_false); + def(AST_UnaryPostfix, return_false); + def(AST_UnaryPrefix, function() { + return this.operator == "void"; + }); + def(AST_Binary, function(pure_getters) { + switch (this.operator) { + case "&&": + return this.left._throw_on_access(pure_getters); + case "||": + return this.left._throw_on_access(pure_getters) + && this.right._throw_on_access(pure_getters); + default: + return false; + } + }) + def(AST_Assign, function(pure_getters) { + return this.operator == "=" + && this.right._throw_on_access(pure_getters); + }) + def(AST_Conditional, function(pure_getters) { + return this.consequent._throw_on_access(pure_getters) + || this.alternative._throw_on_access(pure_getters); + }) + def(AST_Seq, function(pure_getters) { + return this.cdr._throw_on_access(pure_getters); + }); + def(AST_SymbolRef, function(pure_getters) { + if (this.is_undefined) return true; + if (!is_strict(pure_getters)) return false; + var fixed = this.fixed_value(); + return !fixed || fixed._throw_on_access(pure_getters); + }); + })(function(node, func) { + node.DEFMETHOD("_throw_on_access", func); + }); + + /* -----[ boolean/negation helpers ]----- */ + + // methods to determine whether an expression has a boolean result type + (function (def){ + var unary_bool = [ "!", "delete" ]; + var binary_bool = [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ]; + def(AST_Node, return_false); + def(AST_UnaryPrefix, function(){ + return member(this.operator, unary_bool); + }); + def(AST_Binary, function(){ + return member(this.operator, binary_bool) || + ( (this.operator == "&&" || this.operator == "||") && + this.left.is_boolean() && this.right.is_boolean() ); + }); + def(AST_Conditional, function(){ + return this.consequent.is_boolean() && this.alternative.is_boolean(); + }); + def(AST_Assign, function(){ + return this.operator == "=" && this.right.is_boolean(); + }); + def(AST_Seq, function(){ + return this.cdr.is_boolean(); + }); + def(AST_True, return_true); + def(AST_False, return_true); + })(function(node, func){ + node.DEFMETHOD("is_boolean", func); + }); + + // methods to determine if an expression has a numeric result type + (function (def){ + def(AST_Node, return_false); + def(AST_Number, return_true); + var unary = makePredicate("+ - ~ ++ --"); + def(AST_Unary, function(){ + return unary(this.operator); + }); + var binary = makePredicate("- * / % & | ^ << >> >>>"); + def(AST_Binary, function(compressor){ + return binary(this.operator) || this.operator == "+" + && this.left.is_number(compressor) + && this.right.is_number(compressor); + }); + def(AST_Assign, function(compressor){ + return binary(this.operator.slice(0, -1)) + || this.operator == "=" && this.right.is_number(compressor); + }); + def(AST_Seq, function(compressor){ + return this.cdr.is_number(compressor); + }); + def(AST_Conditional, function(compressor){ + return this.consequent.is_number(compressor) && this.alternative.is_number(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("is_number", func); + }); + + // methods to determine if an expression has a string result type + (function (def){ + def(AST_Node, return_false); + def(AST_String, return_true); + def(AST_UnaryPrefix, function(){ + return this.operator == "typeof"; + }); + def(AST_Binary, function(compressor){ + return this.operator == "+" && + (this.left.is_string(compressor) || this.right.is_string(compressor)); + }); + def(AST_Assign, function(compressor){ + return (this.operator == "=" || this.operator == "+=") && this.right.is_string(compressor); + }); + def(AST_Seq, function(compressor){ + return this.cdr.is_string(compressor); + }); + def(AST_Conditional, function(compressor){ + return this.consequent.is_string(compressor) && this.alternative.is_string(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("is_string", func); + }); + + var unary_side_effects = makePredicate("delete ++ --"); + + function is_lhs(node, parent) { + if (parent instanceof AST_Unary && unary_side_effects(parent.operator)) return parent.expression; + if (parent instanceof AST_Assign && parent.left === node) return node; + } + + (function (def){ + AST_Node.DEFMETHOD("resolve_defines", function(compressor) { + if (!compressor.option("global_defs")) return; + var def = this._find_defs(compressor, ""); + if (def) { + var node, parent = this, level = 0; + do { + node = parent; + parent = compressor.parent(level++); + } while (parent instanceof AST_PropAccess && parent.expression === node); + if (is_lhs(node, parent)) { + compressor.warn('global_defs ' + this.print_to_string() + ' redefined [{file}:{line},{col}]', this.start); + } else { + return def; + } + } + }); + function to_node(value, orig) { + if (value instanceof AST_Node) return make_node(value.CTOR, orig, value); + if (Array.isArray(value)) return make_node(AST_Array, orig, { + elements: value.map(function(value) { + return to_node(value, orig); + }) + }); + if (value && typeof value == "object") { + var props = []; + for (var key in value) { + props.push(make_node(AST_ObjectKeyVal, orig, { + key: key, + value: to_node(value[key], orig) + })); + } + return make_node(AST_Object, orig, { + properties: props + }); + } + return make_node_from_constant(value, orig); + } + def(AST_Node, noop); + def(AST_Dot, function(compressor, suffix){ + return this.expression._find_defs(compressor, "." + this.property + suffix); + }); + def(AST_SymbolRef, function(compressor, suffix){ + if (!this.global()) return; + var name; + var defines = compressor.option("global_defs"); + if (defines && HOP(defines, (name = this.name + suffix))) { + var node = to_node(defines[name], this); + var top = compressor.find_parent(AST_Toplevel); + node.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) { + node.scope = top; + node.thedef = top.def_global(node); + } + })); + return node; + } + }); + })(function(node, func){ + node.DEFMETHOD("_find_defs", func); + }); + + function best_of_expression(ast1, ast2) { + return ast1.print_to_string().length > + ast2.print_to_string().length + ? ast2 : ast1; + } + + function best_of_statement(ast1, ast2) { + return best_of_expression(make_node(AST_SimpleStatement, ast1, { + body: ast1 + }), make_node(AST_SimpleStatement, ast2, { + body: ast2 + })).body; + } + + function best_of(compressor, ast1, ast2) { + return (first_in_statement(compressor) ? best_of_statement : best_of_expression)(ast1, ast2); + } + + // methods to evaluate a constant expression + (function (def){ + // If the node has been successfully reduced to a constant, + // then its value is returned; otherwise the element itself + // is returned. + // They can be distinguished as constant value is never a + // descendant of AST_Node. + AST_Node.DEFMETHOD("evaluate", function(compressor){ + if (!compressor.option("evaluate")) return this; + try { + var val = this._eval(compressor); + return !val || val instanceof RegExp || typeof val != "object" ? val : this; + } catch(ex) { + if (ex !== def) throw ex; + return this; + } + }); + var unaryPrefix = makePredicate("! ~ - + void"); + AST_Node.DEFMETHOD("is_constant", function(){ + // Accomodate when compress option evaluate=false + // as well as the common constant expressions !0 and -1 + if (this instanceof AST_Constant) { + return !(this instanceof AST_RegExp); + } else { + return this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant + && unaryPrefix(this.operator); + } + }); + // Obtain the constant value of an expression already known to be constant. + // Result only valid iff this.is_constant() is true. + AST_Node.DEFMETHOD("constant_value", function(compressor){ + // Accomodate when option evaluate=false. + if (this instanceof AST_Constant && !(this instanceof AST_RegExp)) { + return this.value; + } + // Accomodate the common constant expressions !0 and -1 when option evaluate=false. + if (this instanceof AST_UnaryPrefix + && this.expression instanceof AST_Constant) switch (this.operator) { + case "!": + return !this.expression.value; + case "~": + return ~this.expression.value; + case "-": + return -this.expression.value; + case "+": + return +this.expression.value; + default: + throw new Error(string_template("Cannot evaluate unary expression {value}", { + value: this.print_to_string() + })); + } + var result = this.evaluate(compressor); + if (result !== this) { + return result; + } + throw new Error(string_template("Cannot evaluate constant [{file}:{line},{col}]", this.start)); + }); + def(AST_Statement, function(){ + throw new Error(string_template("Cannot evaluate a statement [{file}:{line},{col}]", this.start)); + }); + def(AST_Lambda, function(){ + throw def; + }); + function ev(node, compressor) { + if (!compressor) throw new Error("Compressor must be passed"); + + return node._eval(compressor); + }; + def(AST_Node, function(){ + throw def; // not constant + }); + def(AST_Constant, function(){ + return this.getValue(); + }); + def(AST_Array, function(compressor){ + if (compressor.option("unsafe")) { + return this.elements.map(function(element) { + return ev(element, compressor); + }); + } + throw def; + }); + def(AST_Object, function(compressor){ + if (compressor.option("unsafe")) { + var val = {}; + for (var i = 0, len = this.properties.length; i < len; i++) { + var prop = this.properties[i]; + var key = prop.key; + if (key instanceof AST_Symbol) { + key = key.name; + } else if (key instanceof AST_Node) { + key = ev(key, compressor); + } + if (typeof Object.prototype[key] === 'function') { + throw def; + } + val[key] = ev(prop.value, compressor); + } + return val; + } + throw def; + }); + def(AST_UnaryPrefix, function(compressor){ + var e = this.expression; + switch (this.operator) { + case "!": return !ev(e, compressor); + case "typeof": + // Function would be evaluated to an array and so typeof would + // incorrectly return 'object'. Hence making is a special case. + if (e instanceof AST_Function) return typeof function(){}; + + e = ev(e, compressor); + + // typeof <RegExp> returns "object" or "function" on different platforms + // so cannot evaluate reliably + if (e instanceof RegExp) throw def; + + return typeof e; + case "void": return void ev(e, compressor); + case "~": return ~ev(e, compressor); + case "-": return -ev(e, compressor); + case "+": return +ev(e, compressor); + } + throw def; + }); + def(AST_Binary, function(c){ + var left = this.left, right = this.right, result; + switch (this.operator) { + case "&&" : result = ev(left, c) && ev(right, c); break; + case "||" : result = ev(left, c) || ev(right, c); break; + case "|" : result = ev(left, c) | ev(right, c); break; + case "&" : result = ev(left, c) & ev(right, c); break; + case "^" : result = ev(left, c) ^ ev(right, c); break; + case "+" : result = ev(left, c) + ev(right, c); break; + case "*" : result = ev(left, c) * ev(right, c); break; + case "/" : result = ev(left, c) / ev(right, c); break; + case "%" : result = ev(left, c) % ev(right, c); break; + case "-" : result = ev(left, c) - ev(right, c); break; + case "<<" : result = ev(left, c) << ev(right, c); break; + case ">>" : result = ev(left, c) >> ev(right, c); break; + case ">>>" : result = ev(left, c) >>> ev(right, c); break; + case "==" : result = ev(left, c) == ev(right, c); break; + case "===" : result = ev(left, c) === ev(right, c); break; + case "!=" : result = ev(left, c) != ev(right, c); break; + case "!==" : result = ev(left, c) !== ev(right, c); break; + case "<" : result = ev(left, c) < ev(right, c); break; + case "<=" : result = ev(left, c) <= ev(right, c); break; + case ">" : result = ev(left, c) > ev(right, c); break; + case ">=" : result = ev(left, c) >= ev(right, c); break; + default: + throw def; + } + if (isNaN(result) && c.find_parent(AST_With)) { + // leave original expression as is + throw def; + } + return result; + }); + def(AST_Conditional, function(compressor){ + return ev(this.condition, compressor) + ? ev(this.consequent, compressor) + : ev(this.alternative, compressor); + }); + def(AST_SymbolRef, function(compressor){ + if (!compressor.option("reduce_vars") || this._evaluating) throw def; + this._evaluating = true; + try { + var fixed = this.fixed_value(); + if (!fixed) throw def; + var value = ev(fixed, compressor); + if (!HOP(fixed, "_eval")) fixed._eval = function() { + return value; + }; + if (value && typeof value == "object" && this.definition().escaped) throw def; + return value; + } finally { + this._evaluating = false; + } + }); + def(AST_PropAccess, function(compressor){ + if (compressor.option("unsafe")) { + var key = this.property; + if (key instanceof AST_Node) { + key = ev(key, compressor); + } + var val = ev(this.expression, compressor); + if (val && HOP(val, key)) { + return val[key]; + } + } + throw def; + }); + })(function(node, func){ + node.DEFMETHOD("_eval", func); + }); + + // method to negate an expression + (function(def){ + function basic_negation(exp) { + return make_node(AST_UnaryPrefix, exp, { + operator: "!", + expression: exp + }); + } + function best(orig, alt, first_in_statement) { + var negated = basic_negation(orig); + if (first_in_statement) { + var stat = make_node(AST_SimpleStatement, alt, { + body: alt + }); + return best_of_expression(negated, stat) === stat ? alt : negated; + } + return best_of_expression(negated, alt); + } + def(AST_Node, function(){ + return basic_negation(this); + }); + def(AST_Statement, function(){ + throw new Error("Cannot negate a statement"); + }); + def(AST_Function, function(){ + return basic_negation(this); + }); + def(AST_UnaryPrefix, function(){ + if (this.operator == "!") + return this.expression; + return basic_negation(this); + }); + def(AST_Seq, function(compressor){ + var self = this.clone(); + self.cdr = self.cdr.negate(compressor); + return self; + }); + def(AST_Conditional, function(compressor, first_in_statement){ + var self = this.clone(); + self.consequent = self.consequent.negate(compressor); + self.alternative = self.alternative.negate(compressor); + return best(this, self, first_in_statement); + }); + def(AST_Binary, function(compressor, first_in_statement){ + var self = this.clone(), op = this.operator; + if (compressor.option("unsafe_comps")) { + switch (op) { + case "<=" : self.operator = ">" ; return self; + case "<" : self.operator = ">=" ; return self; + case ">=" : self.operator = "<" ; return self; + case ">" : self.operator = "<=" ; return self; + } + } + switch (op) { + case "==" : self.operator = "!="; return self; + case "!=" : self.operator = "=="; return self; + case "===": self.operator = "!=="; return self; + case "!==": self.operator = "==="; return self; + case "&&": + self.operator = "||"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + case "||": + self.operator = "&&"; + self.left = self.left.negate(compressor, first_in_statement); + self.right = self.right.negate(compressor); + return best(this, self, first_in_statement); + } + return basic_negation(this); + }); + })(function(node, func){ + node.DEFMETHOD("negate", function(compressor, first_in_statement){ + return func.call(this, compressor, first_in_statement); + }); + }); + + AST_Call.DEFMETHOD("has_pure_annotation", function(compressor) { + if (!compressor.option("side_effects")) return false; + if (this.pure !== undefined) return this.pure; + var pure = false; + var comments, last_comment; + if (this.start + && (comments = this.start.comments_before) + && comments.length + && /[@#]__PURE__/.test((last_comment = comments[comments.length - 1]).value)) { + pure = last_comment; + } + return this.pure = pure; + }); + + // determine if expression has side effects + (function(def){ + def(AST_Node, return_true); + + def(AST_EmptyStatement, return_false); + def(AST_Constant, return_false); + def(AST_This, return_false); + + def(AST_Call, function(compressor){ + if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) return true; + for (var i = this.args.length; --i >= 0;) { + if (this.args[i].has_side_effects(compressor)) + return true; + } + return false; + }); + + function any(list, compressor) { + for (var i = list.length; --i >= 0;) + if (list[i].has_side_effects(compressor)) + return true; + return false; + } + + def(AST_Block, function(compressor){ + return any(this.body, compressor); + }); + def(AST_Switch, function(compressor){ + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_Case, function(compressor){ + return this.expression.has_side_effects(compressor) + || any(this.body, compressor); + }); + def(AST_Try, function(compressor){ + return any(this.body, compressor) + || this.bcatch && this.bcatch.has_side_effects(compressor) + || this.bfinally && this.bfinally.has_side_effects(compressor); + }); + def(AST_If, function(compressor){ + return this.condition.has_side_effects(compressor) + || this.body && this.body.has_side_effects(compressor) + || this.alternative && this.alternative.has_side_effects(compressor); + }); + def(AST_LabeledStatement, function(compressor){ + return this.body.has_side_effects(compressor); + }); + def(AST_SimpleStatement, function(compressor){ + return this.body.has_side_effects(compressor); + }); + def(AST_Defun, return_true); + def(AST_Function, return_false); + def(AST_Binary, function(compressor){ + return this.left.has_side_effects(compressor) + || this.right.has_side_effects(compressor); + }); + def(AST_Assign, return_true); + def(AST_Conditional, function(compressor){ + return this.condition.has_side_effects(compressor) + || this.consequent.has_side_effects(compressor) + || this.alternative.has_side_effects(compressor); + }); + def(AST_Unary, function(compressor){ + return unary_side_effects(this.operator) + || this.expression.has_side_effects(compressor); + }); + def(AST_SymbolRef, function(compressor){ + return this.undeclared(); + }); + def(AST_Object, function(compressor){ + return any(this.properties, compressor); + }); + def(AST_ObjectProperty, function(compressor){ + return this.value.has_side_effects(compressor); + }); + def(AST_Array, function(compressor){ + return any(this.elements, compressor); + }); + def(AST_Dot, function(compressor){ + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor); + }); + def(AST_Sub, function(compressor){ + return this.expression.may_throw_on_access(compressor) + || this.expression.has_side_effects(compressor) + || this.property.has_side_effects(compressor); + }); + def(AST_Seq, function(compressor){ + return this.car.has_side_effects(compressor) + || this.cdr.has_side_effects(compressor); + }); + })(function(node, func){ + node.DEFMETHOD("has_side_effects", func); + }); + + // tell me if a statement aborts + function aborts(thing) { + return thing && thing.aborts(); + }; + (function(def){ + def(AST_Statement, return_null); + def(AST_Jump, return_this); + function block_aborts(){ + var n = this.body.length; + return n > 0 && aborts(this.body[n - 1]); + }; + def(AST_BlockStatement, block_aborts); + def(AST_SwitchBranch, block_aborts); + def(AST_If, function(){ + return this.alternative && aborts(this.body) && aborts(this.alternative) && this; + }); + })(function(node, func){ + node.DEFMETHOD("aborts", func); + }); + + /* -----[ optimizers ]----- */ + + OPT(AST_Directive, function(self, compressor){ + if (compressor.has_directive(self.value) !== self) { + return make_node(AST_EmptyStatement, self); + } + return self; + }); + + OPT(AST_Debugger, function(self, compressor){ + if (compressor.option("drop_debugger")) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_LabeledStatement, function(self, compressor){ + if (self.body instanceof AST_Break + && compressor.loopcontrol_target(self.body) === self.body) { + return make_node(AST_EmptyStatement, self); + } + return self.label.references.length == 0 ? self.body : self; + }); + + OPT(AST_Block, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + return self; + }); + + OPT(AST_BlockStatement, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + switch (self.body.length) { + case 1: return self.body[0]; + case 0: return make_node(AST_EmptyStatement, self); + } + return self; + }); + + AST_Scope.DEFMETHOD("drop_unused", function(compressor){ + var self = this; + if (compressor.has_directive("use asm")) return self; + var toplevel = compressor.option("toplevel"); + if (compressor.option("unused") + && (!(self instanceof AST_Toplevel) || toplevel) + && !self.uses_eval + && !self.uses_with) { + var assign_as_unused = !/keep_assign/.test(compressor.option("unused")); + var drop_funcs = /funcs/.test(toplevel); + var drop_vars = /vars/.test(toplevel); + if (!(self instanceof AST_Toplevel) || toplevel == true) { + drop_funcs = drop_vars = true; + } + var in_use = []; + var in_use_ids = Object.create(null); // avoid expensive linear scans of in_use + if (self instanceof AST_Toplevel && compressor.top_retain) { + self.variables.each(function(def) { + if (compressor.top_retain(def) && !(def.id in in_use_ids)) { + in_use_ids[def.id] = true; + in_use.push(def); + } + }); + } + var initializations = new Dictionary(); + // pass 1: find out which symbols are directly used in + // this scope (not in nested scopes). + var scope = this; + var tw = new TreeWalker(function(node, descend){ + if (node !== self) { + if (node instanceof AST_Defun) { + if (!drop_funcs && scope === self) { + var node_def = node.name.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + initializations.add(node.name.name, node); + return true; // don't go in nested scopes + } + if (node instanceof AST_Definitions && scope === self) { + node.definitions.forEach(function(def){ + if (!drop_vars) { + var node_def = def.name.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + if (def.value) { + initializations.add(def.name.name, def.value); + if (def.value.has_side_effects(compressor)) { + def.value.walk(tw); + } + } + }); + return true; + } + if (assign_as_unused + && node instanceof AST_Assign + && node.operator == "=" + && node.left instanceof AST_SymbolRef + && !is_reference_const(node.left) + && scope === self) { + node.right.walk(tw); + return true; + } + if (node instanceof AST_SymbolRef) { + var node_def = node.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + return true; + } + if (node instanceof AST_Scope) { + var save_scope = scope; + scope = node; + descend(); + scope = save_scope; + return true; + } + } + }); + self.walk(tw); + // pass 2: for every used symbol we need to walk its + // initialization code to figure out if it uses other + // symbols (that may not be in_use). + for (var i = 0; i < in_use.length; ++i) { + in_use[i].orig.forEach(function(decl){ + // undeclared globals will be instanceof AST_SymbolRef + var init = initializations.get(decl.name); + if (init) init.forEach(function(init){ + var tw = new TreeWalker(function(node){ + if (node instanceof AST_SymbolRef) { + var node_def = node.definition(); + if (!(node_def.id in in_use_ids)) { + in_use_ids[node_def.id] = true; + in_use.push(node_def); + } + } + }); + init.walk(tw); + }); + }); + } + // pass 3: we should drop declarations not in_use + var tt = new TreeTransformer( + function before(node, descend, in_list) { + if (node instanceof AST_Function + && node.name + && !compressor.option("keep_fnames")) { + var def = node.name.definition(); + // any declarations with same name will overshadow + // name of this anonymous function and can therefore + // never be used anywhere + if (!(def.id in in_use_ids) || def.orig.length > 1) + node.name = null; + } + if (node instanceof AST_Lambda && !(node instanceof AST_Accessor)) { + var trim = !compressor.option("keep_fargs"); + for (var a = node.argnames, i = a.length; --i >= 0;) { + var sym = a[i]; + if (!(sym.definition().id in in_use_ids)) { + sym.__unused = true; + if (trim) { + a.pop(); + compressor[sym.unreferenced() ? "warn" : "info"]("Dropping unused function argument {name} [{file}:{line},{col}]", { + name : sym.name, + file : sym.start.file, + line : sym.start.line, + col : sym.start.col + }); + } + } + else { + trim = false; + } + } + } + if (drop_funcs && node instanceof AST_Defun && node !== self) { + if (!(node.name.definition().id in in_use_ids)) { + compressor[node.name.unreferenced() ? "warn" : "info"]("Dropping unused function {name} [{file}:{line},{col}]", { + name : node.name.name, + file : node.name.start.file, + line : node.name.start.line, + col : node.name.start.col + }); + return make_node(AST_EmptyStatement, node); + } + return node; + } + if (drop_vars && node instanceof AST_Definitions && !(tt.parent() instanceof AST_ForIn && tt.parent().init === node)) { + var def = node.definitions.filter(function(def){ + if (def.value) def.value = def.value.transform(tt); + var sym = def.name.definition(); + if (sym.id in in_use_ids) return true; + if (sym.orig[0] instanceof AST_SymbolCatch) { + def.value = def.value && def.value.drop_side_effect_free(compressor); + return true; + } + var w = { + name : def.name.name, + file : def.name.start.file, + line : def.name.start.line, + col : def.name.start.col + }; + if (def.value && (def._unused_side_effects = def.value.drop_side_effect_free(compressor))) { + compressor.warn("Side effects in initialization of unused variable {name} [{file}:{line},{col}]", w); + return true; + } + compressor[def.name.unreferenced() ? "warn" : "info"]("Dropping unused variable {name} [{file}:{line},{col}]", w); + return false; + }); + // place uninitialized names at the start + def = mergeSort(def, function(a, b){ + if (!a.value && b.value) return -1; + if (!b.value && a.value) return 1; + return 0; + }); + // for unused names whose initialization has + // side effects, we can cascade the init. code + // into the next one, or next statement. + var side_effects = []; + for (var i = 0; i < def.length;) { + var x = def[i]; + if (x._unused_side_effects) { + side_effects.push(x._unused_side_effects); + def.splice(i, 1); + } else { + if (side_effects.length > 0) { + side_effects.push(x.value); + x.value = AST_Seq.from_array(side_effects); + side_effects = []; + } + ++i; + } + } + if (side_effects.length > 0) { + side_effects = make_node(AST_BlockStatement, node, { + body: [ make_node(AST_SimpleStatement, node, { + body: AST_Seq.from_array(side_effects) + }) ] + }); + } else { + side_effects = null; + } + if (def.length == 0 && !side_effects) { + return make_node(AST_EmptyStatement, node); + } + if (def.length == 0) { + return in_list ? MAP.splice(side_effects.body) : side_effects; + } + node.definitions = def; + if (side_effects) { + side_effects.body.unshift(node); + return in_list ? MAP.splice(side_effects.body) : side_effects; + } + return node; + } + if (drop_vars && assign_as_unused + && node instanceof AST_Assign + && node.operator == "=" + && node.left instanceof AST_SymbolRef) { + var def = node.left.definition(); + if (!(def.id in in_use_ids) + && self.variables.get(def.name) === def) { + return maintain_this_binding(tt.parent(), node, node.right.transform(tt)); + } + } + // certain combination of unused name + side effect leads to: + // https://github.com/mishoo/UglifyJS2/issues/44 + // https://github.com/mishoo/UglifyJS2/issues/1830 + // that's an invalid AST. + // We fix it at this stage by moving the `var` outside the `for`. + if (node instanceof AST_For) { + descend(node, this); + if (node.init instanceof AST_BlockStatement) { + var block = node.init; + node.init = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } else if (is_empty(node.init)) { + node.init = null; + } + return node; + } + if (node instanceof AST_LabeledStatement && node.body instanceof AST_For) { + descend(node, this); + if (node.body instanceof AST_BlockStatement) { + var block = node.body; + node.body = block.body.pop(); + block.body.push(node); + return in_list ? MAP.splice(block.body) : block; + } + return node; + } + if (node instanceof AST_Scope && node !== self) + return node; + } + ); + self.transform(tt); + } + }); + + AST_Scope.DEFMETHOD("hoist_declarations", function(compressor){ + var self = this; + if (compressor.has_directive("use asm")) return self; + var hoist_funs = compressor.option("hoist_funs"); + var hoist_vars = compressor.option("hoist_vars"); + if (hoist_funs || hoist_vars) { + var dirs = []; + var hoisted = []; + var vars = new Dictionary(), vars_found = 0, var_decl = 0; + // let's count var_decl first, we seem to waste a lot of + // space if we hoist `var` when there's only one. + self.walk(new TreeWalker(function(node){ + if (node instanceof AST_Scope && node !== self) + return true; + if (node instanceof AST_Var) { + ++var_decl; + return true; + } + })); + hoist_vars = hoist_vars && var_decl > 1; + var tt = new TreeTransformer( + function before(node) { + if (node !== self) { + if (node instanceof AST_Directive) { + dirs.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Defun && hoist_funs) { + hoisted.push(node); + return make_node(AST_EmptyStatement, node); + } + if (node instanceof AST_Var && hoist_vars) { + node.definitions.forEach(function(def){ + vars.set(def.name.name, def); + ++vars_found; + }); + var seq = node.to_assignments(compressor); + var p = tt.parent(); + if (p instanceof AST_ForIn && p.init === node) { + if (seq == null) { + var def = node.definitions[0].name; + return make_node(AST_SymbolRef, def, def); + } + return seq; + } + if (p instanceof AST_For && p.init === node) { + return seq; + } + if (!seq) return make_node(AST_EmptyStatement, node); + return make_node(AST_SimpleStatement, node, { + body: seq + }); + } + if (node instanceof AST_Scope) + return node; // to avoid descending in nested scopes + } + } + ); + self = self.transform(tt); + if (vars_found > 0) { + // collect only vars which don't show up in self's arguments list + var defs = []; + vars.each(function(def, name){ + if (self instanceof AST_Lambda + && find_if(function(x){ return x.name == def.name.name }, + self.argnames)) { + vars.del(name); + } else { + def = def.clone(); + def.value = null; + defs.push(def); + vars.set(name, def); + } + }); + if (defs.length > 0) { + // try to merge in assignments + for (var i = 0; i < self.body.length;) { + if (self.body[i] instanceof AST_SimpleStatement) { + var expr = self.body[i].body, sym, assign; + if (expr instanceof AST_Assign + && expr.operator == "=" + && (sym = expr.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = expr.right; + remove(defs, def); + defs.push(def); + self.body.splice(i, 1); + continue; + } + if (expr instanceof AST_Seq + && (assign = expr.car) instanceof AST_Assign + && assign.operator == "=" + && (sym = assign.left) instanceof AST_Symbol + && vars.has(sym.name)) + { + var def = vars.get(sym.name); + if (def.value) break; + def.value = assign.right; + remove(defs, def); + defs.push(def); + self.body[i].body = expr.cdr; + continue; + } + } + if (self.body[i] instanceof AST_EmptyStatement) { + self.body.splice(i, 1); + continue; + } + if (self.body[i] instanceof AST_BlockStatement) { + var tmp = [ i, 1 ].concat(self.body[i].body); + self.body.splice.apply(self.body, tmp); + continue; + } + break; + } + defs = make_node(AST_Var, self, { + definitions: defs + }); + hoisted.push(defs); + }; + } + self.body = dirs.concat(hoisted, self.body); + } + return self; + }); + + // drop_side_effect_free() + // remove side-effect-free parts which only affects return value + (function(def){ + // Drop side-effect-free elements from an array of expressions. + // Returns an array of expressions with side-effects or null + // if all elements were dropped. Note: original array may be + // returned if nothing changed. + function trim(nodes, compressor, first_in_statement) { + var ret = [], changed = false; + for (var i = 0, len = nodes.length; i < len; i++) { + var node = nodes[i].drop_side_effect_free(compressor, first_in_statement); + changed |= node !== nodes[i]; + if (node) { + ret.push(node); + first_in_statement = false; + } + } + return changed ? ret.length ? ret : null : nodes; + } + + def(AST_Node, return_this); + def(AST_Constant, return_null); + def(AST_This, return_null); + def(AST_Call, function(compressor, first_in_statement){ + if (!this.has_pure_annotation(compressor) && compressor.pure_funcs(this)) { + if (this.expression instanceof AST_Function + && (!this.expression.name || !this.expression.name.definition().references.length)) { + var node = this.clone(); + node.expression = node.expression.process_expression(false, compressor); + return node; + } + return this; + } + if (this.pure) { + compressor.warn("Dropping __PURE__ call [{file}:{line},{col}]", this.start); + this.pure.value = this.pure.value.replace(/[@#]__PURE__/g, ' '); + } + var args = trim(this.args, compressor, first_in_statement); + return args && AST_Seq.from_array(args); + }); + def(AST_Accessor, return_null); + def(AST_Function, return_null); + def(AST_Binary, function(compressor, first_in_statement){ + var right = this.right.drop_side_effect_free(compressor); + if (!right) return this.left.drop_side_effect_free(compressor, first_in_statement); + switch (this.operator) { + case "&&": + case "||": + if (right === this.right) return this; + var node = this.clone(); + node.right = right; + return node; + default: + var left = this.left.drop_side_effect_free(compressor, first_in_statement); + if (!left) return this.right.drop_side_effect_free(compressor, first_in_statement); + return make_node(AST_Seq, this, { + car: left, + cdr: right + }); + } + }); + def(AST_Assign, return_this); + def(AST_Conditional, function(compressor){ + var consequent = this.consequent.drop_side_effect_free(compressor); + var alternative = this.alternative.drop_side_effect_free(compressor); + if (consequent === this.consequent && alternative === this.alternative) return this; + if (!consequent) return alternative ? make_node(AST_Binary, this, { + operator: "||", + left: this.condition, + right: alternative + }) : this.condition.drop_side_effect_free(compressor); + if (!alternative) return make_node(AST_Binary, this, { + operator: "&&", + left: this.condition, + right: consequent + }); + var node = this.clone(); + node.consequent = consequent; + node.alternative = alternative; + return node; + }); + def(AST_Unary, function(compressor, first_in_statement){ + if (unary_side_effects(this.operator)) return this; + if (this.operator == "typeof" && this.expression instanceof AST_SymbolRef) return null; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (first_in_statement + && this instanceof AST_UnaryPrefix + && is_iife_call(expression)) { + if (expression === this.expression && this.operator.length === 1) return this; + return make_node(AST_UnaryPrefix, this, { + operator: this.operator.length === 1 ? this.operator : "!", + expression: expression + }); + } + return expression; + }); + def(AST_SymbolRef, function() { + return this.undeclared() ? this : null; + }); + def(AST_Object, function(compressor, first_in_statement){ + var values = trim(this.properties, compressor, first_in_statement); + return values && AST_Seq.from_array(values); + }); + def(AST_ObjectProperty, function(compressor, first_in_statement){ + return this.value.drop_side_effect_free(compressor, first_in_statement); + }); + def(AST_Array, function(compressor, first_in_statement){ + var values = trim(this.elements, compressor, first_in_statement); + return values && AST_Seq.from_array(values); + }); + def(AST_Dot, function(compressor, first_in_statement){ + if (this.expression.may_throw_on_access(compressor)) return this; + return this.expression.drop_side_effect_free(compressor, first_in_statement); + }); + def(AST_Sub, function(compressor, first_in_statement){ + if (this.expression.may_throw_on_access(compressor)) return this; + var expression = this.expression.drop_side_effect_free(compressor, first_in_statement); + if (!expression) return this.property.drop_side_effect_free(compressor, first_in_statement); + var property = this.property.drop_side_effect_free(compressor); + if (!property) return expression; + return make_node(AST_Seq, this, { + car: expression, + cdr: property + }); + }); + def(AST_Seq, function(compressor){ + var cdr = this.cdr.drop_side_effect_free(compressor); + if (cdr === this.cdr) return this; + if (!cdr) return this.car; + return make_node(AST_Seq, this, { + car: this.car, + cdr: cdr + }); + }); + })(function(node, func){ + node.DEFMETHOD("drop_side_effect_free", func); + }); + + OPT(AST_SimpleStatement, function(self, compressor){ + if (compressor.option("side_effects")) { + var body = self.body; + var node = body.drop_side_effect_free(compressor, true); + if (!node) { + compressor.warn("Dropping side-effect-free statement [{file}:{line},{col}]", self.start); + return make_node(AST_EmptyStatement, self); + } + if (node !== body) { + return make_node(AST_SimpleStatement, self, { body: node }); + } + } + return self; + }); + + OPT(AST_DWLoop, function(self, compressor){ + if (!compressor.option("loops")) return self; + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + return make_node(AST_For, self, { + body: self.body + }); + } + if (compressor.option("dead_code") && self instanceof AST_While) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + if (self instanceof AST_Do) { + var has_loop_control = false; + var tw = new TreeWalker(function(node) { + if (node instanceof AST_Scope || has_loop_control) return true; + if (node instanceof AST_LoopControl && tw.loopcontrol_target(node) === self) + return has_loop_control = true; + }); + var parent = compressor.parent(); + (parent instanceof AST_LabeledStatement ? parent : self).walk(tw); + if (!has_loop_control) return self.body; + } + } + if (self instanceof AST_While) { + return make_node(AST_For, self, self).optimize(compressor); + } + return self; + }); + + function if_break_in_loop(self, compressor) { + function drop_it(rest) { + rest = as_statement_array(rest); + if (self.body instanceof AST_BlockStatement) { + self.body = self.body.clone(); + self.body.body = rest.concat(self.body.body.slice(1)); + self.body = self.body.transform(compressor); + } else { + self.body = make_node(AST_BlockStatement, self.body, { + body: rest + }).transform(compressor); + } + if_break_in_loop(self, compressor); + } + var first = self.body instanceof AST_BlockStatement ? self.body.body[0] : self.body; + if (first instanceof AST_If) { + if (first.body instanceof AST_Break + && compressor.loopcontrol_target(first.body) === compressor.self()) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition.negate(compressor), + }); + } else { + self.condition = first.condition.negate(compressor); + } + drop_it(first.alternative); + } + else if (first.alternative instanceof AST_Break + && compressor.loopcontrol_target(first.alternative) === compressor.self()) { + if (self.condition) { + self.condition = make_node(AST_Binary, self.condition, { + left: self.condition, + operator: "&&", + right: first.condition, + }); + } else { + self.condition = first.condition; + } + drop_it(first.body); + } + } + }; + + OPT(AST_For, function(self, compressor){ + if (!compressor.option("loops")) return self; + if (self.condition) { + var cond = self.condition.evaluate(compressor); + if (compressor.option("dead_code") && !cond) { + var a = []; + if (self.init instanceof AST_Statement) { + a.push(self.init); + } + else if (self.init) { + a.push(make_node(AST_SimpleStatement, self.init, { + body: self.init + })); + } + extract_declarations_from_unreachable_code(compressor, self.body, a); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + if (cond !== self.condition) { + cond = make_node_from_constant(cond, self.condition).transform(compressor); + self.condition = best_of_expression(cond, self.condition); + } + } + if_break_in_loop(self, compressor); + return self; + }); + + OPT(AST_If, function(self, compressor){ + if (is_empty(self.alternative)) self.alternative = null; + + if (!compressor.option("conditionals")) return self; + // if condition can be statically determined, warn and drop + // one of the blocks. note, statically determined implies + // “has no side effectsâ€; also it doesn't work for cases like + // `x && true`, though it probably should. + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + if (self.alternative) { + extract_declarations_from_unreachable_code(compressor, self.alternative, a); + } + a.push(self.body); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.condition.start); + if (compressor.option("dead_code")) { + var a = []; + extract_declarations_from_unreachable_code(compressor, self.body, a); + if (self.alternative) a.push(self.alternative); + return make_node(AST_BlockStatement, self, { body: a }).optimize(compressor); + } + } + cond = make_node_from_constant(cond, self.condition).transform(compressor); + self.condition = best_of_expression(cond, self.condition); + } + var negated = self.condition.negate(compressor); + var self_condition_length = self.condition.print_to_string().length; + var negated_length = negated.print_to_string().length; + var negated_is_best = negated_length < self_condition_length; + if (self.alternative && negated_is_best) { + negated_is_best = false; // because we already do the switch here. + // no need to swap values of self_condition_length and negated_length + // here because they are only used in an equality comparison later on. + self.condition = negated; + var tmp = self.body; + self.body = self.alternative || make_node(AST_EmptyStatement, self); + self.alternative = tmp; + } + if (is_empty(self.body) && is_empty(self.alternative)) { + return make_node(AST_SimpleStatement, self.condition, { + body: self.condition.clone() + }).optimize(compressor); + } + if (self.body instanceof AST_SimpleStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.body, + alternative : self.alternative.body + }) + }).optimize(compressor); + } + if (is_empty(self.alternative) && self.body instanceof AST_SimpleStatement) { + if (self_condition_length === negated_length && !negated_is_best + && self.condition instanceof AST_Binary && self.condition.operator == "||") { + // although the code length of self.condition and negated are the same, + // negated does not require additional surrounding parentheses. + // see https://github.com/mishoo/UglifyJS2/issues/979 + negated_is_best = true; + } + if (negated_is_best) return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : negated, + right : self.body.body + }) + }).optimize(compressor); + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "&&", + left : self.condition, + right : self.body.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_EmptyStatement + && self.alternative instanceof AST_SimpleStatement) { + return make_node(AST_SimpleStatement, self, { + body: make_node(AST_Binary, self, { + operator : "||", + left : self.condition, + right : self.alternative.body + }) + }).optimize(compressor); + } + if (self.body instanceof AST_Exit + && self.alternative instanceof AST_Exit + && self.body.TYPE == self.alternative.TYPE) { + return make_node(self.body.CTOR, self, { + value: make_node(AST_Conditional, self, { + condition : self.condition, + consequent : self.body.value || make_node(AST_Undefined, self.body), + alternative : self.alternative.value || make_node(AST_Undefined, self.alternative) + }).transform(compressor) + }).optimize(compressor); + } + if (self.body instanceof AST_If + && !self.body.alternative + && !self.alternative) { + self = make_node(AST_If, self, { + condition: make_node(AST_Binary, self.condition, { + operator: "&&", + left: self.condition, + right: self.body.condition + }), + body: self.body.body, + alternative: null + }); + } + if (aborts(self.body)) { + if (self.alternative) { + var alt = self.alternative; + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, alt ] + }).optimize(compressor); + } + } + if (aborts(self.alternative)) { + var body = self.body; + self.body = self.alternative; + self.condition = negated_is_best ? negated : self.condition.negate(compressor); + self.alternative = null; + return make_node(AST_BlockStatement, self, { + body: [ self, body ] + }).optimize(compressor); + } + return self; + }); + + OPT(AST_Switch, function(self, compressor){ + if (!compressor.option("switches")) return self; + var branch; + var value = self.expression.evaluate(compressor); + if (value !== self.expression) { + var expression = make_node_from_constant(value, self.expression).transform(compressor); + self.expression = best_of_expression(expression, self.expression); + } + if (!compressor.option("dead_code")) return self; + var decl = []; + var body = []; + var default_branch; + var exact_match; + for (var i = 0, len = self.body.length; i < len && !exact_match; i++) { + branch = self.body[i]; + if (branch instanceof AST_Default) { + if (!default_branch) { + default_branch = branch; + } else { + eliminate_branch(branch, body[body.length - 1]); + } + } else if (value !== self.expression) { + var exp = branch.expression.evaluate(compressor); + if (exp === value) { + exact_match = branch; + if (default_branch) { + var default_index = body.indexOf(default_branch); + body.splice(default_index, 1); + eliminate_branch(default_branch, body[default_index - 1]); + default_branch = null; + } + } else if (exp !== branch.expression) { + eliminate_branch(branch, body[body.length - 1]); + continue; + } + } + if (aborts(branch)) { + var prev = body[body.length - 1]; + if (aborts(prev) && prev.body.length == branch.body.length + && make_node(AST_BlockStatement, prev, prev).equivalent_to(make_node(AST_BlockStatement, branch, branch))) { + prev.body = []; + } + } + body.push(branch); + } + while (i < len) eliminate_branch(self.body[i++], body[body.length - 1]); + if (body.length > 0) { + body[0].body = decl.concat(body[0].body); + } + self.body = body; + while (branch = body[body.length - 1]) { + var stat = branch.body[branch.body.length - 1]; + if (stat instanceof AST_Break && compressor.loopcontrol_target(stat) === self) + branch.body.pop(); + if (branch.body.length || branch instanceof AST_Case + && (default_branch || branch.expression.has_side_effects(compressor))) break; + if (body.pop() === default_branch) default_branch = null; + } + if (body.length == 0) { + return make_node(AST_BlockStatement, self, { + body: decl.concat(make_node(AST_SimpleStatement, self.expression, { + body: self.expression + })) + }).optimize(compressor); + } + if (body.length == 1 && (body[0] === exact_match || body[0] === default_branch)) { + var has_break = false; + var tw = new TreeWalker(function(node) { + if (has_break + || node instanceof AST_Lambda + || node instanceof AST_SimpleStatement) return true; + if (node instanceof AST_Break && tw.loopcontrol_target(node) === self) + has_break = true; + }); + self.walk(tw); + if (!has_break) { + body = body[0].body.slice(); + body.unshift(make_node(AST_SimpleStatement, self.expression, { + body: self.expression + })); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + } + return self; + + function eliminate_branch(branch, prev) { + if (prev && !aborts(prev)) { + prev.body = prev.body.concat(branch.body); + } else { + extract_declarations_from_unreachable_code(compressor, branch, decl); + } + } + }); + + OPT(AST_Try, function(self, compressor){ + self.body = tighten_body(self.body, compressor); + if (self.bcatch && self.bfinally && all(self.bfinally.body, is_empty)) self.bfinally = null; + if (all(self.body, is_empty)) { + var body = []; + if (self.bcatch) extract_declarations_from_unreachable_code(compressor, self.bcatch, body); + if (self.bfinally) body = body.concat(self.bfinally.body); + return make_node(AST_BlockStatement, self, { + body: body + }).optimize(compressor); + } + return self; + }); + + AST_Definitions.DEFMETHOD("remove_initializers", function(){ + this.definitions.forEach(function(def){ def.value = null }); + }); + + AST_Definitions.DEFMETHOD("to_assignments", function(compressor){ + var reduce_vars = compressor.option("reduce_vars"); + var assignments = this.definitions.reduce(function(a, def){ + if (def.value) { + var name = make_node(AST_SymbolRef, def.name, def.name); + a.push(make_node(AST_Assign, def, { + operator : "=", + left : name, + right : def.value + })); + if (reduce_vars) name.definition().fixed = false; + } + return a; + }, []); + if (assignments.length == 0) return null; + return AST_Seq.from_array(assignments); + }); + + OPT(AST_Definitions, function(self, compressor){ + if (self.definitions.length == 0) + return make_node(AST_EmptyStatement, self); + return self; + }); + + OPT(AST_Call, function(self, compressor){ + var exp = self.expression; + if (compressor.option("reduce_vars") + && exp instanceof AST_SymbolRef) { + var def = exp.definition(); + var fixed = exp.fixed_value(); + if (fixed instanceof AST_Defun) { + def.fixed = fixed = make_node(AST_Function, fixed, fixed).clone(true); + } + if (fixed instanceof AST_Function) { + exp = fixed; + if (compressor.option("unused") + && def.references.length == 1 + && !(def.scope.uses_arguments + && def.orig[0] instanceof AST_SymbolFunarg) + && !def.scope.uses_eval + && compressor.find_parent(AST_Scope) === def.scope) { + self.expression = exp; + } + } + } + if (compressor.option("unused") + && exp instanceof AST_Function + && !exp.uses_arguments + && !exp.uses_eval) { + var pos = 0, last = 0; + for (var i = 0, len = self.args.length; i < len; i++) { + var trim = i >= exp.argnames.length; + if (trim || exp.argnames[i].__unused) { + var node = self.args[i].drop_side_effect_free(compressor); + if (node) { + self.args[pos++] = node; + } else if (!trim) { + self.args[pos++] = make_node(AST_Number, self.args[i], { + value: 0 + }); + continue; + } + } else { + self.args[pos++] = self.args[i]; + } + last = pos; + } + self.args.length = last; + } + if (compressor.option("unsafe")) { + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Array": + if (self.args.length != 1) { + return make_node(AST_Array, self, { + elements: self.args + }).optimize(compressor); + } + break; + case "Object": + if (self.args.length == 0) { + return make_node(AST_Object, self, { + properties: [] + }); + } + break; + case "String": + if (self.args.length == 0) return make_node(AST_String, self, { + value: "" + }); + if (self.args.length <= 1) return make_node(AST_Binary, self, { + left: self.args[0], + operator: "+", + right: make_node(AST_String, self, { value: "" }) + }).optimize(compressor); + break; + case "Number": + if (self.args.length == 0) return make_node(AST_Number, self, { + value: 0 + }); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "+" + }).optimize(compressor); + case "Boolean": + if (self.args.length == 0) return make_node(AST_False, self); + if (self.args.length == 1) return make_node(AST_UnaryPrefix, self, { + expression: make_node(AST_UnaryPrefix, self, { + expression: self.args[0], + operator: "!" + }), + operator: "!" + }).optimize(compressor); + break; + case "Function": + // new Function() => function(){} + if (self.args.length == 0) return make_node(AST_Function, self, { + argnames: [], + body: [] + }); + if (all(self.args, function(x){ return x instanceof AST_String })) { + // quite a corner-case, but we can handle it: + // https://github.com/mishoo/UglifyJS2/issues/203 + // if the code argument is a constant, then we can minify it. + try { + var code = "(function(" + self.args.slice(0, -1).map(function(arg){ + return arg.value; + }).join(",") + "){" + self.args[self.args.length - 1].value + "})()"; + var ast = parse(code); + ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); + var comp = new Compressor(compressor.options); + ast = ast.transform(comp); + ast.figure_out_scope({ screw_ie8: compressor.option("screw_ie8") }); + ast.mangle_names(); + var fun; + try { + ast.walk(new TreeWalker(function(node){ + if (node instanceof AST_Lambda) { + fun = node; + throw ast; + } + })); + } catch(ex) { + if (ex !== ast) throw ex; + }; + if (!fun) return self; + var args = fun.argnames.map(function(arg, i){ + return make_node(AST_String, self.args[i], { + value: arg.print_to_string() + }); + }); + var code = OutputStream(); + AST_BlockStatement.prototype._codegen.call(fun, fun, code); + code = code.toString().replace(/^\{|\}$/g, ""); + args.push(make_node(AST_String, self.args[self.args.length - 1], { + value: code + })); + self.args = args; + return self; + } catch(ex) { + if (ex instanceof JS_Parse_Error) { + compressor.warn("Error parsing code passed to new Function [{file}:{line},{col}]", self.args[self.args.length - 1].start); + compressor.warn(ex.toString()); + } else { + console.log(ex); + throw ex; + } + } + } + break; + } + } + else if (exp instanceof AST_Dot && exp.property == "toString" && self.args.length == 0) { + return make_node(AST_Binary, self, { + left: make_node(AST_String, self, { value: "" }), + operator: "+", + right: exp.expression + }).optimize(compressor); + } + else if (exp instanceof AST_Dot && exp.expression instanceof AST_Array && exp.property == "join") EXIT: { + var separator; + if (self.args.length > 0) { + separator = self.args[0].evaluate(compressor); + if (separator === self.args[0]) break EXIT; // not a constant + } + var elements = []; + var consts = []; + exp.expression.elements.forEach(function(el) { + var value = el.evaluate(compressor); + if (value !== el) { + consts.push(value); + } else { + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + consts.length = 0; + } + elements.push(el); + } + }); + if (consts.length > 0) { + elements.push(make_node(AST_String, self, { + value: consts.join(separator) + })); + } + if (elements.length == 0) return make_node(AST_String, self, { value: "" }); + if (elements.length == 1) { + if (elements[0].is_string(compressor)) { + return elements[0]; + } + return make_node(AST_Binary, elements[0], { + operator : "+", + left : make_node(AST_String, self, { value: "" }), + right : elements[0] + }); + } + if (separator == "") { + var first; + if (elements[0].is_string(compressor) + || elements[1].is_string(compressor)) { + first = elements.shift(); + } else { + first = make_node(AST_String, self, { value: "" }); + } + return elements.reduce(function(prev, el){ + return make_node(AST_Binary, el, { + operator : "+", + left : prev, + right : el + }); + }, first).optimize(compressor); + } + // need this awkward cloning to not affect original element + // best_of will decide which one to get through. + var node = self.clone(); + node.expression = node.expression.clone(); + node.expression.expression = node.expression.expression.clone(); + node.expression.expression.elements = elements; + return best_of(compressor, self, node); + } + else if (exp instanceof AST_Dot && exp.expression.is_string(compressor) && exp.property == "charAt") { + var arg = self.args[0]; + var index = arg ? arg.evaluate(compressor) : 0; + if (index !== arg) { + return make_node(AST_Sub, exp, { + expression: exp.expression, + property: make_node_from_constant(index | 0, arg || exp) + }).optimize(compressor); + } + } + } + if (exp instanceof AST_Function) { + if (exp.body[0] instanceof AST_Return) { + var value = exp.body[0].value; + if (!value || value.is_constant()) { + var args = self.args.concat(value || make_node(AST_Undefined, self)); + return AST_Seq.from_array(args).transform(compressor); + } + } + if (compressor.option("side_effects") && all(exp.body, is_empty)) { + var args = self.args.concat(make_node(AST_Undefined, self)); + return AST_Seq.from_array(args).transform(compressor); + } + } + if (compressor.option("drop_console")) { + if (exp instanceof AST_PropAccess) { + var name = exp.expression; + while (name.expression) { + name = name.expression; + } + if (name instanceof AST_SymbolRef + && name.name == "console" + && name.undeclared()) { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + } + if (compressor.option("negate_iife") + && compressor.parent() instanceof AST_SimpleStatement + && is_iife_call(self)) { + return self.negate(compressor, true); + } + return self; + }); + + OPT(AST_New, function(self, compressor){ + if (compressor.option("unsafe")) { + var exp = self.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) { + switch (exp.name) { + case "Object": + case "RegExp": + case "Function": + case "Error": + case "Array": + return make_node(AST_Call, self, self).transform(compressor); + } + } + } + return self; + }); + + OPT(AST_Seq, function(self, compressor){ + if (!compressor.option("side_effects")) + return self; + self.car = self.car.drop_side_effect_free(compressor, first_in_statement(compressor)); + if (!self.car) return maintain_this_binding(compressor.parent(), self, self.cdr); + if (compressor.option("cascade")) { + var left; + if (self.car instanceof AST_Assign + && !self.car.left.has_side_effects(compressor)) { + left = self.car.left; + } else if (self.car instanceof AST_Unary + && (self.car.operator == "++" || self.car.operator == "--")) { + left = self.car.expression; + } + if (left + && !(left instanceof AST_SymbolRef + && (left.definition().orig[0] instanceof AST_SymbolLambda + || is_reference_const(left)))) { + var parent, field; + var cdr = self.cdr; + while (true) { + if (cdr.equivalent_to(left)) { + var car = self.car instanceof AST_UnaryPostfix ? make_node(AST_UnaryPrefix, self.car, { + operator: self.car.operator, + expression: left + }) : self.car; + if (parent) { + parent[field] = car; + return self.cdr; + } + return car; + } + if (cdr instanceof AST_Binary && !(cdr instanceof AST_Assign)) { + if (cdr.left.is_constant()) { + if (cdr.operator == "||" || cdr.operator == "&&") break; + field = "right"; + } else { + field = "left"; + } + } else if (cdr instanceof AST_Call + || cdr instanceof AST_Unary && !unary_side_effects(cdr.operator)) { + field = "expression"; + } else break; + parent = cdr; + cdr = cdr[field]; + } + } + } + if (is_undefined(self.cdr, compressor)) { + return make_node(AST_UnaryPrefix, self, { + operator : "void", + expression : self.car + }); + } + return self; + }); + + AST_Unary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.expression instanceof AST_Seq) { + var seq = this.expression; + var x = seq.to_array(); + var e = this.clone(); + e.expression = x.pop(); + x.push(e); + seq = AST_Seq.from_array(x).transform(compressor); + return seq; + } + } + return this; + }); + + OPT(AST_UnaryPostfix, function(self, compressor){ + return self.lift_sequences(compressor); + }); + + OPT(AST_UnaryPrefix, function(self, compressor){ + var e = self.expression; + if (self.operator == "delete" + && !(e instanceof AST_SymbolRef + || e instanceof AST_PropAccess + || e instanceof AST_NaN + || e instanceof AST_Infinity + || e instanceof AST_Undefined)) { + if (e instanceof AST_Seq) { + e = e.to_array(); + e.push(make_node(AST_True, self)); + return AST_Seq.from_array(e).optimize(compressor); + } + return make_node(AST_Seq, self, { + car: e, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + var seq = self.lift_sequences(compressor); + if (seq !== self) { + return seq; + } + if (compressor.option("side_effects") && self.operator == "void") { + e = e.drop_side_effect_free(compressor); + if (e) { + self.expression = e; + return self; + } else { + return make_node(AST_Undefined, self).optimize(compressor); + } + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + switch (self.operator) { + case "!": + if (e instanceof AST_UnaryPrefix && e.operator == "!") { + // !!foo ==> foo, if we're in boolean context + return e.expression; + } + if (e instanceof AST_Binary) { + self = best_of(compressor, self, e.negate(compressor, first_in_statement(compressor))); + } + break; + case "typeof": + // typeof always returns a non-empty string, thus it's + // always true in booleans + compressor.warn("Boolean expression always true [{file}:{line},{col}]", self.start); + return (e instanceof AST_SymbolRef ? make_node(AST_True, self) : make_node(AST_Seq, self, { + car: e, + cdr: make_node(AST_True, self) + })).optimize(compressor); + } + } + if (self.operator == "-" && e instanceof AST_Infinity) { + e = e.transform(compressor); + } + if (e instanceof AST_Binary + && (self.operator == "+" || self.operator == "-") + && (e.operator == "*" || e.operator == "/" || e.operator == "%")) { + return make_node(AST_Binary, self, { + operator: e.operator, + left: make_node(AST_UnaryPrefix, e.left, { + operator: self.operator, + expression: e.left + }), + right: e.right + }); + } + // avoids infinite recursion of numerals + if (self.operator != "-" + || !(e instanceof AST_Number || e instanceof AST_Infinity)) { + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + } + return self; + }); + + AST_Binary.DEFMETHOD("lift_sequences", function(compressor){ + if (compressor.option("sequences")) { + if (this.left instanceof AST_Seq) { + var seq = this.left; + var x = seq.to_array(); + var e = this.clone(); + e.left = x.pop(); + x.push(e); + return AST_Seq.from_array(x).optimize(compressor); + } + if (this.right instanceof AST_Seq && !this.left.has_side_effects(compressor)) { + var assign = this.operator == "=" && this.left instanceof AST_SymbolRef; + var root = this.right.clone(); + var cursor, seq = root; + while (assign || !seq.car.has_side_effects(compressor)) { + cursor = seq; + if (seq.cdr instanceof AST_Seq) { + seq = seq.cdr = seq.cdr.clone(); + } else break; + } + if (cursor) { + var e = this.clone(); + e.right = cursor.cdr; + cursor.cdr = e; + return root.optimize(compressor); + } + } + } + return this; + }); + + var commutativeOperators = makePredicate("== === != !== * & | ^"); + + OPT(AST_Binary, function(self, compressor){ + function reversible() { + return self.left.is_constant() + || self.right.is_constant() + || !self.left.has_side_effects(compressor) + && !self.right.has_side_effects(compressor); + } + function reverse(op) { + if (reversible()) { + if (op) self.operator = op; + var tmp = self.left; + self.left = self.right; + self.right = tmp; + } + } + if (commutativeOperators(self.operator)) { + if (self.right.is_constant() + && !self.left.is_constant()) { + // if right is a constant, whatever side effects the + // left side might have could not influence the + // result. hence, force switch. + + if (!(self.left instanceof AST_Binary + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + reverse(); + } + } + } + self = self.lift_sequences(compressor); + if (compressor.option("comparisons")) switch (self.operator) { + case "===": + case "!==": + if ((self.left.is_string(compressor) && self.right.is_string(compressor)) || + (self.left.is_number(compressor) && self.right.is_number(compressor)) || + (self.left.is_boolean() && self.right.is_boolean())) { + self.operator = self.operator.substr(0, 2); + } + // XXX: intentionally falling down to the next case + case "==": + case "!=": + // "undefined" == typeof x => undefined === x + if (self.left instanceof AST_String + && self.left.value == "undefined" + && self.right instanceof AST_UnaryPrefix + && self.right.operator == "typeof") { + var expr = self.right.expression; + if (expr instanceof AST_SymbolRef ? !expr.undeclared() + : !(expr instanceof AST_PropAccess) || compressor.option("screw_ie8")) { + self.right = expr; + self.left = make_node(AST_Undefined, self.left).optimize(compressor); + if (self.operator.length == 2) self.operator += "="; + } + } + break; + } + if (compressor.option("booleans") && self.operator == "+" && compressor.in_boolean_context()) { + var ll = self.left.evaluate(compressor); + var rr = self.right.evaluate(compressor); + if (ll && typeof ll == "string") { + compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.right, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + if (rr && typeof rr == "string") { + compressor.warn("+ in boolean context always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + } + if (compressor.option("comparisons") && self.is_boolean()) { + if (!(compressor.parent() instanceof AST_Binary) + || compressor.parent() instanceof AST_Assign) { + var negated = make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: self.negate(compressor, first_in_statement(compressor)) + }); + self = best_of(compressor, self, negated); + } + if (compressor.option("unsafe_comps")) { + switch (self.operator) { + case "<": reverse(">"); break; + case "<=": reverse(">="); break; + } + } + } + if (self.operator == "+") { + if (self.right instanceof AST_String + && self.right.getValue() == "" + && self.left.is_string(compressor)) { + return self.left; + } + if (self.left instanceof AST_String + && self.left.getValue() == "" + && self.right.is_string(compressor)) { + return self.right; + } + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.left instanceof AST_String + && self.left.left.getValue() == "" + && self.right.is_string(compressor)) { + self.left = self.left.right; + return self.transform(compressor); + } + } + if (compressor.option("evaluate")) { + switch (self.operator) { + case "&&": + var ll = self.left.evaluate(compressor); + if (!ll) { + compressor.warn("Condition left of && always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor); + } else if (ll !== self.left) { + compressor.warn("Condition left of && always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor); + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + var rr = self.right.evaluate(compressor); + if (!rr) { + compressor.warn("Boolean && always false [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_False, self) + }).optimize(compressor); + } else if (rr !== self.right) { + compressor.warn("Dropping side-effect-free && in boolean context [{file}:{line},{col}]", self.start); + return self.left.optimize(compressor); + } + } + break; + case "||": + var ll = self.left.evaluate(compressor); + if (!ll) { + compressor.warn("Condition left of || always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.right).optimize(compressor); + } else if (ll !== self.left) { + compressor.warn("Condition left of || always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.left).optimize(compressor); + } + if (compressor.option("booleans") && compressor.in_boolean_context()) { + var rr = self.right.evaluate(compressor); + if (!rr) { + compressor.warn("Dropping side-effect-free || in boolean context [{file}:{line},{col}]", self.start); + return self.left.optimize(compressor); + } else if (rr !== self.right) { + compressor.warn("Boolean || always true [{file}:{line},{col}]", self.start); + return make_node(AST_Seq, self, { + car: self.left, + cdr: make_node(AST_True, self) + }).optimize(compressor); + } + } + break; + } + var associative = true; + switch (self.operator) { + case "+": + // "foo" + ("bar" + x) => "foobar" + x + if (self.left instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.left instanceof AST_Constant + && self.right.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_String, self.left, { + value: "" + self.left.getValue() + self.right.left.getValue(), + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (x + "foo") + "bar" => x + "foobar" + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.right instanceof AST_Constant + && self.left.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: self.left.left, + right: make_node(AST_String, self.right, { + value: "" + self.left.right.getValue() + self.right.getValue(), + start: self.left.right.start, + end: self.right.end + }) + }); + } + // (x + "foo") + ("bar" + y) => (x + "foobar") + y + if (self.left instanceof AST_Binary + && self.left.operator == "+" + && self.left.is_string(compressor) + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == "+" + && self.right.left instanceof AST_Constant + && self.right.is_string(compressor)) { + self = make_node(AST_Binary, self, { + operator: "+", + left: make_node(AST_Binary, self.left, { + operator: "+", + left: self.left.left, + right: make_node(AST_String, self.left.right, { + value: "" + self.left.right.getValue() + self.right.left.getValue(), + start: self.left.right.start, + end: self.right.left.end + }) + }), + right: self.right.right + }); + } + // a + -b => a - b + if (self.right instanceof AST_UnaryPrefix + && self.right.operator == "-" + && self.left.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.left, + right: self.right.expression + }); + break; + } + // -a + b => b - a + if (self.left instanceof AST_UnaryPrefix + && self.left.operator == "-" + && reversible() + && self.right.is_number(compressor)) { + self = make_node(AST_Binary, self, { + operator: "-", + left: self.right, + right: self.left.expression + }); + break; + } + case "*": + associative = compressor.option("unsafe_math"); + case "&": + case "|": + case "^": + // a + +b => +b + a + if (self.left.is_number(compressor) + && self.right.is_number(compressor) + && reversible() + && !(self.left instanceof AST_Binary + && self.left.operator != self.operator + && PRECEDENCE[self.left.operator] >= PRECEDENCE[self.operator])) { + var reversed = make_node(AST_Binary, self, { + operator: self.operator, + left: self.right, + right: self.left + }); + if (self.right instanceof AST_Constant + && !(self.left instanceof AST_Constant)) { + self = best_of(compressor, reversed, self); + } else { + self = best_of(compressor, self, reversed); + } + } + if (associative && self.is_number(compressor)) { + // a + (b + c) => (a + b) + c + if (self.right instanceof AST_Binary + && self.right.operator == self.operator) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left, + right: self.right.left, + start: self.left.start, + end: self.right.left.end + }), + right: self.right.right + }); + } + // (n + 2) + 3 => 5 + n + // (2 * n) * 3 => 6 + n + if (self.right instanceof AST_Constant + && self.left instanceof AST_Binary + && self.left.operator == self.operator) { + if (self.left.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.left, + right: self.right, + start: self.left.left.start, + end: self.right.end + }), + right: self.left.right + }); + } else if (self.left.right instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: self.left.right, + right: self.right, + start: self.left.right.start, + end: self.right.end + }), + right: self.left.left + }); + } + } + // (a | 1) | (2 | d) => (3 | a) | b + if (self.left instanceof AST_Binary + && self.left.operator == self.operator + && self.left.right instanceof AST_Constant + && self.right instanceof AST_Binary + && self.right.operator == self.operator + && self.right.left instanceof AST_Constant) { + self = make_node(AST_Binary, self, { + operator: self.operator, + left: make_node(AST_Binary, self.left, { + operator: self.operator, + left: make_node(AST_Binary, self.left.left, { + operator: self.operator, + left: self.left.right, + right: self.right.left, + start: self.left.right.start, + end: self.right.left.end + }), + right: self.left.left + }), + right: self.right.right + }); + } + } + } + } + // x && (y && z) ==> x && y && z + // x || (y || z) ==> x || y || z + // x + ("y" + z) ==> x + "y" + z + // "x" + (y + "z")==> "x" + y + "z" + if (self.right instanceof AST_Binary + && self.right.operator == self.operator + && (self.operator == "&&" + || self.operator == "||" + || (self.operator == "+" + && (self.right.left.is_string(compressor) + || (self.left.is_string(compressor) + && self.right.right.is_string(compressor)))))) + { + self.left = make_node(AST_Binary, self.left, { + operator : self.operator, + left : self.left, + right : self.right.left + }); + self.right = self.right.right; + return self.transform(compressor); + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + OPT(AST_SymbolRef, function(self, compressor){ + var def = self.resolve_defines(compressor); + if (def) { + return def.optimize(compressor); + } + // testing against !self.scope.uses_with first is an optimization + if (compressor.option("screw_ie8") + && self.undeclared() + && (!self.scope.uses_with || !compressor.find_parent(AST_With))) { + switch (self.name) { + case "undefined": + return make_node(AST_Undefined, self).optimize(compressor); + case "NaN": + return make_node(AST_NaN, self).optimize(compressor); + case "Infinity": + return make_node(AST_Infinity, self).optimize(compressor); + } + } + if (compressor.option("evaluate") + && compressor.option("reduce_vars") + && is_lhs(self, compressor.parent()) !== self) { + var d = self.definition(); + var fixed = self.fixed_value(); + if (fixed) { + if (d.should_replace === undefined) { + var init = fixed.evaluate(compressor); + if (init !== fixed && (compressor.option("unsafe_regexp") || !(init instanceof RegExp))) { + init = make_node_from_constant(init, fixed); + var value = init.optimize(compressor).print_to_string().length; + var fn; + if (has_symbol_ref(fixed)) { + fn = function() { + var result = init.optimize(compressor); + return result === init ? result.clone(true) : result; + }; + } else { + value = Math.min(value, fixed.print_to_string().length); + fn = function() { + var result = best_of_expression(init.optimize(compressor), fixed); + return result === init || result === fixed ? result.clone(true) : result; + }; + } + var name = d.name.length; + var overhead = 0; + if (compressor.option("unused") && (!d.global || compressor.option("toplevel"))) { + overhead = (name + 2 + value) / d.references.length; + } + d.should_replace = value <= name + overhead ? fn : false; + } else { + d.should_replace = false; + } + } + if (d.should_replace) { + return d.should_replace(); + } + } + } + return self; + + function has_symbol_ref(value) { + var found; + value.walk(new TreeWalker(function(node) { + if (node instanceof AST_SymbolRef) found = true; + if (found) return true; + })); + return found; + } + }); + + function is_atomic(lhs, self) { + return lhs instanceof AST_SymbolRef || lhs.TYPE === self.TYPE; + } + + OPT(AST_Undefined, function(self, compressor){ + if (compressor.option("unsafe")) { + var undef = find_variable(compressor, "undefined"); + if (undef) { + var ref = make_node(AST_SymbolRef, self, { + name : "undefined", + scope : undef.scope, + thedef : undef + }); + ref.is_undefined = true; + return ref; + } + } + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + return make_node(AST_UnaryPrefix, self, { + operator: "void", + expression: make_node(AST_Number, self, { + value: 0 + }) + }); + }); + + OPT(AST_Infinity, function(self, compressor){ + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && is_atomic(lhs, self)) return self; + if (compressor.option("keep_infinity") + && !(lhs && !is_atomic(lhs, self)) + && !find_variable(compressor, "Infinity")) + return self; + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 1 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + }); + + OPT(AST_NaN, function(self, compressor){ + var lhs = is_lhs(compressor.self(), compressor.parent()); + if (lhs && !is_atomic(lhs, self) + || find_variable(compressor, "NaN")) { + return make_node(AST_Binary, self, { + operator: "/", + left: make_node(AST_Number, self, { + value: 0 + }), + right: make_node(AST_Number, self, { + value: 0 + }) + }); + } + return self; + }); + + var ASSIGN_OPS = [ '+', '-', '/', '*', '%', '>>', '<<', '>>>', '|', '^', '&' ]; + var ASSIGN_OPS_COMMUTATIVE = [ '*', '|', '^', '&' ]; + OPT(AST_Assign, function(self, compressor){ + self = self.lift_sequences(compressor); + if (self.operator == "=" && self.left instanceof AST_SymbolRef && self.right instanceof AST_Binary) { + // x = expr1 OP expr2 + if (self.right.left instanceof AST_SymbolRef + && self.right.left.name == self.left.name + && member(self.right.operator, ASSIGN_OPS)) { + // x = x - 2 ---> x -= 2 + self.operator = self.right.operator + "="; + self.right = self.right.right; + } + else if (self.right.right instanceof AST_SymbolRef + && self.right.right.name == self.left.name + && member(self.right.operator, ASSIGN_OPS_COMMUTATIVE) + && !self.right.left.has_side_effects(compressor)) { + // x = 2 & x ---> x &= 2 + self.operator = self.right.operator + "="; + self.right = self.right.left; + } + } + return self; + }); + + OPT(AST_Conditional, function(self, compressor){ + if (!compressor.option("conditionals")) return self; + if (self.condition instanceof AST_Seq) { + var car = self.condition.car; + self.condition = self.condition.cdr; + return AST_Seq.cons(car, self); + } + var cond = self.condition.evaluate(compressor); + if (cond !== self.condition) { + if (cond) { + compressor.warn("Condition always true [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.consequent); + } else { + compressor.warn("Condition always false [{file}:{line},{col}]", self.start); + return maintain_this_binding(compressor.parent(), self, self.alternative); + } + } + var negated = cond.negate(compressor, first_in_statement(compressor)); + if (best_of(compressor, cond, negated) === negated) { + self = make_node(AST_Conditional, self, { + condition: negated, + consequent: self.alternative, + alternative: self.consequent + }); + } + var condition = self.condition; + var consequent = self.consequent; + var alternative = self.alternative; + // x?x:y --> x||y + if (condition instanceof AST_SymbolRef + && consequent instanceof AST_SymbolRef + && condition.definition() === consequent.definition()) { + return make_node(AST_Binary, self, { + operator: "||", + left: condition, + right: alternative + }); + } + // if (foo) exp = something; else exp = something_else; + // | + // v + // exp = foo ? something : something_else; + if (consequent instanceof AST_Assign + && alternative instanceof AST_Assign + && consequent.operator == alternative.operator + && consequent.left.equivalent_to(alternative.left) + && (!self.condition.has_side_effects(compressor) + || consequent.operator == "=" + && !consequent.left.has_side_effects(compressor))) { + return make_node(AST_Assign, self, { + operator: consequent.operator, + left: consequent.left, + right: make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.right, + alternative: alternative.right + }) + }); + } + // x ? y(a) : y(b) --> y(x ? a : b) + if (consequent instanceof AST_Call + && alternative.TYPE === consequent.TYPE + && consequent.args.length == 1 + && alternative.args.length == 1 + && consequent.expression.equivalent_to(alternative.expression) + && !consequent.expression.has_side_effects(compressor)) { + consequent.args[0] = make_node(AST_Conditional, self, { + condition: self.condition, + consequent: consequent.args[0], + alternative: alternative.args[0] + }); + return consequent; + } + // x?y?z:a:a --> x&&y?z:a + if (consequent instanceof AST_Conditional + && consequent.alternative.equivalent_to(alternative)) { + return make_node(AST_Conditional, self, { + condition: make_node(AST_Binary, self, { + left: self.condition, + operator: "&&", + right: consequent.condition + }), + consequent: consequent.consequent, + alternative: alternative + }); + } + // x ? y : y --> x, y + if (consequent.equivalent_to(alternative)) { + return make_node(AST_Seq, self, { + car: self.condition, + cdr: consequent + }).optimize(compressor); + } + + if (is_true(self.consequent)) { + if (is_false(self.alternative)) { + // c ? true : false ---> !!c + return booleanize(self.condition); + } + // c ? true : x ---> !!c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition), + right: self.alternative + }); + } + if (is_false(self.consequent)) { + if (is_true(self.alternative)) { + // c ? false : true ---> !c + return booleanize(self.condition.negate(compressor)); + } + // c ? false : x ---> !c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition.negate(compressor)), + right: self.alternative + }); + } + if (is_true(self.alternative)) { + // c ? x : true ---> !c || x + return make_node(AST_Binary, self, { + operator: "||", + left: booleanize(self.condition.negate(compressor)), + right: self.consequent + }); + } + if (is_false(self.alternative)) { + // c ? x : false ---> !!c && x + return make_node(AST_Binary, self, { + operator: "&&", + left: booleanize(self.condition), + right: self.consequent + }); + } + + return self; + + function booleanize(node) { + if (node.is_boolean()) return node; + // !!expression + return make_node(AST_UnaryPrefix, node, { + operator: "!", + expression: node.negate(compressor) + }); + } + + // AST_True or !0 + function is_true(node) { + return node instanceof AST_True + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !node.expression.value); + } + // AST_False or !1 + function is_false(node) { + return node instanceof AST_False + || (node instanceof AST_UnaryPrefix + && node.operator == "!" + && node.expression instanceof AST_Constant + && !!node.expression.value); + } + }); + + OPT(AST_Boolean, function(self, compressor){ + if (compressor.option("booleans")) { + var p = compressor.parent(); + if (p instanceof AST_Binary && (p.operator == "==" + || p.operator == "!=")) { + compressor.warn("Non-strict equality against boolean: {operator} {value} [{file}:{line},{col}]", { + operator : p.operator, + value : self.value, + file : p.start.file, + line : p.start.line, + col : p.start.col, + }); + return make_node(AST_Number, self, { + value: +self.value + }); + } + return make_node(AST_UnaryPrefix, self, { + operator: "!", + expression: make_node(AST_Number, self, { + value: 1 - self.value + }) + }); + } + return self; + }); + + OPT(AST_Sub, function(self, compressor){ + var prop = self.property; + if (prop instanceof AST_String && compressor.option("properties")) { + prop = prop.getValue(); + if (RESERVED_WORDS(prop) ? compressor.option("screw_ie8") : is_identifier_string(prop)) { + return make_node(AST_Dot, self, { + expression : self.expression, + property : prop + }).optimize(compressor); + } + var v = parseFloat(prop); + if (!isNaN(v) && v.toString() == prop) { + self.property = make_node(AST_Number, self.property, { + value: v + }); + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + OPT(AST_Dot, function(self, compressor){ + var def = self.resolve_defines(compressor); + if (def) { + return def.optimize(compressor); + } + var prop = self.property; + if (RESERVED_WORDS(prop) && !compressor.option("screw_ie8")) { + return make_node(AST_Sub, self, { + expression : self.expression, + property : make_node(AST_String, self, { + value: prop + }) + }).optimize(compressor); + } + if (compressor.option("unsafe_proto") + && self.expression instanceof AST_Dot + && self.expression.property == "prototype") { + var exp = self.expression.expression; + if (exp instanceof AST_SymbolRef && exp.undeclared()) switch (exp.name) { + case "Array": + self.expression = make_node(AST_Array, self.expression, { + elements: [] + }); + break; + case "Object": + self.expression = make_node(AST_Object, self.expression, { + properties: [] + }); + break; + case "String": + self.expression = make_node(AST_String, self.expression, { + value: "" + }); + break; + } + } + var ev = self.evaluate(compressor); + if (ev !== self) { + ev = make_node_from_constant(ev, self).optimize(compressor); + return best_of(compressor, ev, self); + } + return self; + }); + + function literals_in_boolean_context(self, compressor) { + if (compressor.option("booleans") && compressor.in_boolean_context()) { + return best_of(compressor, self, make_node(AST_Seq, self, { + car: self, + cdr: make_node(AST_True, self) + }).optimize(compressor)); + } + return self; + }; + OPT(AST_Array, literals_in_boolean_context); + OPT(AST_Object, literals_in_boolean_context); + OPT(AST_RegExp, literals_in_boolean_context); + + OPT(AST_Return, function(self, compressor){ + if (self.value && is_undefined(self.value, compressor)) { + self.value = null; + } + return self; + }); + + OPT(AST_VarDef, function(self, compressor){ + var defines = compressor.option("global_defs"); + if (defines && HOP(defines, self.name.name)) { + compressor.warn('global_defs ' + self.name.name + ' redefined [{file}:{line},{col}]', self.start); + } + return self; + }); + +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +// a small wrapper around fitzgen's source-map library +function SourceMap(options) { + options = defaults(options, { + file : null, + root : null, + orig : null, + + orig_line_diff : 0, + dest_line_diff : 0, + }); + var generator = new MOZ_SourceMap.SourceMapGenerator({ + file : options.file, + sourceRoot : options.root + }); + var orig_map = options.orig && new MOZ_SourceMap.SourceMapConsumer(options.orig); + + if (orig_map && Array.isArray(options.orig.sources)) { + orig_map._sources.toArray().forEach(function(source) { + var sourceContent = orig_map.sourceContentFor(source, true); + if (sourceContent) { + generator.setSourceContent(source, sourceContent); + } + }); + } + + function add(source, gen_line, gen_col, orig_line, orig_col, name) { + if (orig_map) { + var info = orig_map.originalPositionFor({ + line: orig_line, + column: orig_col + }); + if (info.source === null) { + return; + } + source = info.source; + orig_line = info.line; + orig_col = info.column; + name = info.name || name; + } + generator.addMapping({ + generated : { line: gen_line + options.dest_line_diff, column: gen_col }, + original : { line: orig_line + options.orig_line_diff, column: orig_col }, + source : source, + name : name + }); + }; + return { + add : add, + get : function() { return generator }, + toString : function() { return JSON.stringify(generator.toJSON()); } + }; +}; + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +(function(){ + + var normalize_directives = function(body) { + var in_directive = true; + + for (var i = 0; i < body.length; i++) { + if (in_directive && body[i] instanceof AST_Statement && body[i].body instanceof AST_String) { + body[i] = new AST_Directive({ + start: body[i].start, + end: body[i].end, + value: body[i].body.value + }); + } else if (in_directive && !(body[i] instanceof AST_Statement && body[i].body instanceof AST_String)) { + in_directive = false; + } + } + + return body; + }; + + var MOZ_TO_ME = { + Program: function(M) { + return new AST_Toplevel({ + start: my_start_token(M), + end: my_end_token(M), + body: normalize_directives(M.body.map(from_moz)) + }); + }, + FunctionDeclaration: function(M) { + return new AST_Defun({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + body: normalize_directives(from_moz(M.body).body) + }); + }, + FunctionExpression: function(M) { + return new AST_Function({ + start: my_start_token(M), + end: my_end_token(M), + name: from_moz(M.id), + argnames: M.params.map(from_moz), + body: normalize_directives(from_moz(M.body).body) + }); + }, + ExpressionStatement: function(M) { + return new AST_SimpleStatement({ + start: my_start_token(M), + end: my_end_token(M), + body: from_moz(M.expression) + }); + }, + TryStatement: function(M) { + var handlers = M.handlers || [M.handler]; + if (handlers.length > 1 || M.guardedHandlers && M.guardedHandlers.length) { + throw new Error("Multiple catch clauses are not supported."); + } + return new AST_Try({ + start : my_start_token(M), + end : my_end_token(M), + body : from_moz(M.block).body, + bcatch : from_moz(handlers[0]), + bfinally : M.finalizer ? new AST_Finally(from_moz(M.finalizer)) : null + }); + }, + Property: function(M) { + var key = M.key; + var args = { + start : my_start_token(key), + end : my_end_token(M.value), + key : key.type == "Identifier" ? key.name : key.value, + value : from_moz(M.value) + }; + if (M.kind == "init") return new AST_ObjectKeyVal(args); + args.key = new AST_SymbolAccessor({ + name: args.key + }); + args.value = new AST_Accessor(args.value); + if (M.kind == "get") return new AST_ObjectGetter(args); + if (M.kind == "set") return new AST_ObjectSetter(args); + }, + ArrayExpression: function(M) { + return new AST_Array({ + start : my_start_token(M), + end : my_end_token(M), + elements : M.elements.map(function(elem){ + return elem === null ? new AST_Hole() : from_moz(elem); + }) + }); + }, + ObjectExpression: function(M) { + return new AST_Object({ + start : my_start_token(M), + end : my_end_token(M), + properties : M.properties.map(function(prop){ + prop.type = "Property"; + return from_moz(prop) + }) + }); + }, + SequenceExpression: function(M) { + return AST_Seq.from_array(M.expressions.map(from_moz)); + }, + MemberExpression: function(M) { + return new (M.computed ? AST_Sub : AST_Dot)({ + start : my_start_token(M), + end : my_end_token(M), + property : M.computed ? from_moz(M.property) : M.property.name, + expression : from_moz(M.object) + }); + }, + SwitchCase: function(M) { + return new (M.test ? AST_Case : AST_Default)({ + start : my_start_token(M), + end : my_end_token(M), + expression : from_moz(M.test), + body : M.consequent.map(from_moz) + }); + }, + VariableDeclaration: function(M) { + return new (M.kind === "const" ? AST_Const : AST_Var)({ + start : my_start_token(M), + end : my_end_token(M), + definitions : M.declarations.map(from_moz) + }); + }, + Literal: function(M) { + var val = M.value, args = { + start : my_start_token(M), + end : my_end_token(M) + }; + if (val === null) return new AST_Null(args); + switch (typeof val) { + case "string": + args.value = val; + return new AST_String(args); + case "number": + args.value = val; + return new AST_Number(args); + case "boolean": + return new (val ? AST_True : AST_False)(args); + default: + var rx = M.regex; + if (rx && rx.pattern) { + // RegExpLiteral as per ESTree AST spec + args.value = new RegExp(rx.pattern, rx.flags).toString(); + } else { + // support legacy RegExp + args.value = M.regex && M.raw ? M.raw : val; + } + return new AST_RegExp(args); + } + }, + Identifier: function(M) { + var p = FROM_MOZ_STACK[FROM_MOZ_STACK.length - 2]; + return new ( p.type == "LabeledStatement" ? AST_Label + : p.type == "VariableDeclarator" && p.id === M ? (p.kind == "const" ? AST_SymbolConst : AST_SymbolVar) + : p.type == "FunctionExpression" ? (p.id === M ? AST_SymbolLambda : AST_SymbolFunarg) + : p.type == "FunctionDeclaration" ? (p.id === M ? AST_SymbolDefun : AST_SymbolFunarg) + : p.type == "CatchClause" ? AST_SymbolCatch + : p.type == "BreakStatement" || p.type == "ContinueStatement" ? AST_LabelRef + : AST_SymbolRef)({ + start : my_start_token(M), + end : my_end_token(M), + name : M.name + }); + } + }; + + MOZ_TO_ME.UpdateExpression = + MOZ_TO_ME.UnaryExpression = function To_Moz_Unary(M) { + var prefix = "prefix" in M ? M.prefix + : M.type == "UnaryExpression" ? true : false; + return new (prefix ? AST_UnaryPrefix : AST_UnaryPostfix)({ + start : my_start_token(M), + end : my_end_token(M), + operator : M.operator, + expression : from_moz(M.argument) + }); + }; + + map("EmptyStatement", AST_EmptyStatement); + map("BlockStatement", AST_BlockStatement, "body@body"); + map("IfStatement", AST_If, "test>condition, consequent>body, alternate>alternative"); + map("LabeledStatement", AST_LabeledStatement, "label>label, body>body"); + map("BreakStatement", AST_Break, "label>label"); + map("ContinueStatement", AST_Continue, "label>label"); + map("WithStatement", AST_With, "object>expression, body>body"); + map("SwitchStatement", AST_Switch, "discriminant>expression, cases@body"); + map("ReturnStatement", AST_Return, "argument>value"); + map("ThrowStatement", AST_Throw, "argument>value"); + map("WhileStatement", AST_While, "test>condition, body>body"); + map("DoWhileStatement", AST_Do, "test>condition, body>body"); + map("ForStatement", AST_For, "init>init, test>condition, update>step, body>body"); + map("ForInStatement", AST_ForIn, "left>init, right>object, body>body"); + map("DebuggerStatement", AST_Debugger); + map("VariableDeclarator", AST_VarDef, "id>name, init>value"); + map("CatchClause", AST_Catch, "param>argname, body%body"); + + map("ThisExpression", AST_This); + map("BinaryExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("LogicalExpression", AST_Binary, "operator=operator, left>left, right>right"); + map("AssignmentExpression", AST_Assign, "operator=operator, left>left, right>right"); + map("ConditionalExpression", AST_Conditional, "test>condition, consequent>consequent, alternate>alternative"); + map("NewExpression", AST_New, "callee>expression, arguments@args"); + map("CallExpression", AST_Call, "callee>expression, arguments@args"); + + def_to_moz(AST_Toplevel, function To_Moz_Program(M) { + return to_moz_scope("Program", M); + }); + + def_to_moz(AST_Defun, function To_Moz_FunctionDeclaration(M) { + return { + type: "FunctionDeclaration", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + body: to_moz_scope("BlockStatement", M) + } + }); + + def_to_moz(AST_Function, function To_Moz_FunctionExpression(M) { + return { + type: "FunctionExpression", + id: to_moz(M.name), + params: M.argnames.map(to_moz), + body: to_moz_scope("BlockStatement", M) + } + }); + + def_to_moz(AST_Directive, function To_Moz_Directive(M) { + return { + type: "ExpressionStatement", + expression: { + type: "Literal", + value: M.value + } + }; + }); + + def_to_moz(AST_SimpleStatement, function To_Moz_ExpressionStatement(M) { + return { + type: "ExpressionStatement", + expression: to_moz(M.body) + }; + }); + + def_to_moz(AST_SwitchBranch, function To_Moz_SwitchCase(M) { + return { + type: "SwitchCase", + test: to_moz(M.expression), + consequent: M.body.map(to_moz) + }; + }); + + def_to_moz(AST_Try, function To_Moz_TryStatement(M) { + return { + type: "TryStatement", + block: to_moz_block(M), + handler: to_moz(M.bcatch), + guardedHandlers: [], + finalizer: to_moz(M.bfinally) + }; + }); + + def_to_moz(AST_Catch, function To_Moz_CatchClause(M) { + return { + type: "CatchClause", + param: to_moz(M.argname), + guard: null, + body: to_moz_block(M) + }; + }); + + def_to_moz(AST_Definitions, function To_Moz_VariableDeclaration(M) { + return { + type: "VariableDeclaration", + kind: M instanceof AST_Const ? "const" : "var", + declarations: M.definitions.map(to_moz) + }; + }); + + def_to_moz(AST_Seq, function To_Moz_SequenceExpression(M) { + return { + type: "SequenceExpression", + expressions: M.to_array().map(to_moz) + }; + }); + + def_to_moz(AST_PropAccess, function To_Moz_MemberExpression(M) { + var isComputed = M instanceof AST_Sub; + return { + type: "MemberExpression", + object: to_moz(M.expression), + computed: isComputed, + property: isComputed ? to_moz(M.property) : {type: "Identifier", name: M.property} + }; + }); + + def_to_moz(AST_Unary, function To_Moz_Unary(M) { + return { + type: M.operator == "++" || M.operator == "--" ? "UpdateExpression" : "UnaryExpression", + operator: M.operator, + prefix: M instanceof AST_UnaryPrefix, + argument: to_moz(M.expression) + }; + }); + + def_to_moz(AST_Binary, function To_Moz_BinaryExpression(M) { + return { + type: M.operator == "&&" || M.operator == "||" ? "LogicalExpression" : "BinaryExpression", + left: to_moz(M.left), + operator: M.operator, + right: to_moz(M.right) + }; + }); + + def_to_moz(AST_Array, function To_Moz_ArrayExpression(M) { + return { + type: "ArrayExpression", + elements: M.elements.map(to_moz) + }; + }); + + def_to_moz(AST_Object, function To_Moz_ObjectExpression(M) { + return { + type: "ObjectExpression", + properties: M.properties.map(to_moz) + }; + }); + + def_to_moz(AST_ObjectProperty, function To_Moz_Property(M) { + var key = { + type: "Literal", + value: M.key instanceof AST_SymbolAccessor ? M.key.name : M.key + }; + var kind; + if (M instanceof AST_ObjectKeyVal) { + kind = "init"; + } else + if (M instanceof AST_ObjectGetter) { + kind = "get"; + } else + if (M instanceof AST_ObjectSetter) { + kind = "set"; + } + return { + type: "Property", + kind: kind, + key: key, + value: to_moz(M.value) + }; + }); + + def_to_moz(AST_Symbol, function To_Moz_Identifier(M) { + var def = M.definition(); + return { + type: "Identifier", + name: def ? def.mangled_name || def.name : M.name + }; + }); + + def_to_moz(AST_RegExp, function To_Moz_RegExpLiteral(M) { + var value = M.value; + return { + type: "Literal", + value: value, + raw: value.toString(), + regex: { + pattern: value.source, + flags: value.toString().match(/[gimuy]*$/)[0] + } + }; + }); + + def_to_moz(AST_Constant, function To_Moz_Literal(M) { + var value = M.value; + if (typeof value === 'number' && (value < 0 || (value === 0 && 1 / value < 0))) { + return { + type: "UnaryExpression", + operator: "-", + prefix: true, + argument: { + type: "Literal", + value: -value, + raw: M.start.raw + } + }; + } + return { + type: "Literal", + value: value, + raw: M.start.raw + }; + }); + + def_to_moz(AST_Atom, function To_Moz_Atom(M) { + return { + type: "Identifier", + name: String(M.value) + }; + }); + + AST_Boolean.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Null.DEFMETHOD("to_mozilla_ast", AST_Constant.prototype.to_mozilla_ast); + AST_Hole.DEFMETHOD("to_mozilla_ast", function To_Moz_ArrayHole() { return null }); + + AST_Block.DEFMETHOD("to_mozilla_ast", AST_BlockStatement.prototype.to_mozilla_ast); + AST_Lambda.DEFMETHOD("to_mozilla_ast", AST_Function.prototype.to_mozilla_ast); + + /* -----[ tools ]----- */ + + function raw_token(moznode) { + if (moznode.type == "Literal") { + return moznode.raw != null ? moznode.raw : moznode.value + ""; + } + } + + function my_start_token(moznode) { + var loc = moznode.loc, start = loc && loc.start; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : start && start.line, + col : start && start.column, + pos : range ? range[0] : moznode.start, + endline : start && start.line, + endcol : start && start.column, + endpos : range ? range[0] : moznode.start, + raw : raw_token(moznode), + }); + }; + + function my_end_token(moznode) { + var loc = moznode.loc, end = loc && loc.end; + var range = moznode.range; + return new AST_Token({ + file : loc && loc.source, + line : end && end.line, + col : end && end.column, + pos : range ? range[1] : moznode.end, + endline : end && end.line, + endcol : end && end.column, + endpos : range ? range[1] : moznode.end, + raw : raw_token(moznode), + }); + }; + + function map(moztype, mytype, propmap) { + var moz_to_me = "function From_Moz_" + moztype + "(M){\n"; + moz_to_me += "return new U2." + mytype.name + "({\n" + + "start: my_start_token(M),\n" + + "end: my_end_token(M)"; + + var me_to_moz = "function To_Moz_" + moztype + "(M){\n"; + me_to_moz += "return {\n" + + "type: " + JSON.stringify(moztype); + + if (propmap) propmap.split(/\s*,\s*/).forEach(function(prop){ + var m = /([a-z0-9$_]+)(=|@|>|%)([a-z0-9$_]+)/i.exec(prop); + if (!m) throw new Error("Can't understand property map: " + prop); + var moz = m[1], how = m[2], my = m[3]; + moz_to_me += ",\n" + my + ": "; + me_to_moz += ",\n" + moz + ": "; + switch (how) { + case "@": + moz_to_me += "M." + moz + ".map(from_moz)"; + me_to_moz += "M." + my + ".map(to_moz)"; + break; + case ">": + moz_to_me += "from_moz(M." + moz + ")"; + me_to_moz += "to_moz(M." + my + ")"; + break; + case "=": + moz_to_me += "M." + moz; + me_to_moz += "M." + my; + break; + case "%": + moz_to_me += "from_moz(M." + moz + ").body"; + me_to_moz += "to_moz_block(M)"; + break; + default: + throw new Error("Can't understand operator in propmap: " + prop); + } + }); + + moz_to_me += "\n})\n}"; + me_to_moz += "\n}\n}"; + + //moz_to_me = parse(moz_to_me).print_to_string({ beautify: true }); + //me_to_moz = parse(me_to_moz).print_to_string({ beautify: true }); + //console.log(moz_to_me); + + moz_to_me = new Function("U2", "my_start_token", "my_end_token", "from_moz", "return(" + moz_to_me + ")")( + exports, my_start_token, my_end_token, from_moz + ); + me_to_moz = new Function("to_moz", "to_moz_block", "to_moz_scope", "return(" + me_to_moz + ")")( + to_moz, to_moz_block, to_moz_scope + ); + MOZ_TO_ME[moztype] = moz_to_me; + def_to_moz(mytype, me_to_moz); + }; + + var FROM_MOZ_STACK = null; + + function from_moz(node) { + FROM_MOZ_STACK.push(node); + var ret = node != null ? MOZ_TO_ME[node.type](node) : null; + FROM_MOZ_STACK.pop(); + return ret; + }; + + AST_Node.from_mozilla_ast = function(node){ + var save_stack = FROM_MOZ_STACK; + FROM_MOZ_STACK = []; + var ast = from_moz(node); + FROM_MOZ_STACK = save_stack; + return ast; + }; + + function set_moz_loc(mynode, moznode, myparent) { + var start = mynode.start; + var end = mynode.end; + if (start.pos != null && end.endpos != null) { + moznode.range = [start.pos, end.endpos]; + } + if (start.line) { + moznode.loc = { + start: {line: start.line, column: start.col}, + end: end.endline ? {line: end.endline, column: end.endcol} : null + }; + if (start.file) { + moznode.loc.source = start.file; + } + } + return moznode; + }; + + function def_to_moz(mytype, handler) { + mytype.DEFMETHOD("to_mozilla_ast", function() { + return set_moz_loc(this, handler(this)); + }); + }; + + function to_moz(node) { + return node != null ? node.to_mozilla_ast() : null; + }; + + function to_moz_block(node) { + return { + type: "BlockStatement", + body: node.body.map(to_moz) + }; + }; + + function to_moz_scope(type, node) { + var body = node.body.map(to_moz); + if (node.body[0] instanceof AST_SimpleStatement && node.body[0].body instanceof AST_String) { + body.unshift(to_moz(new AST_EmptyStatement(node.body[0]))); + } + return { + type: type, + body: body + }; + }; +})(); + +/*********************************************************************** + + A JavaScript tokenizer / parser / beautifier / compressor. + https://github.com/mishoo/UglifyJS2 + + -------------------------------- (C) --------------------------------- + + Author: Mihai Bazon + <mihai.bazon@gmail.com> + http://mihai.bazon.net/blog + + Distributed under the BSD license: + + Copyright 2012 (c) Mihai Bazon <mihai.bazon@gmail.com> + + 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. + + THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “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 HOLDER 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. + + ***********************************************************************/ + +"use strict"; + +function find_builtins() { + // NaN will be included due to Number.NaN + var a = [ + "null", + "true", + "false", + "Infinity", + "-Infinity", + "undefined", + ]; + [ Object, Array, Function, Number, + String, Boolean, Error, Math, + Date, RegExp + ].forEach(function(ctor){ + Object.getOwnPropertyNames(ctor).map(add); + if (ctor.prototype) { + Object.getOwnPropertyNames(ctor.prototype).map(add); + } + }); + function add(name) { + push_uniq(a, name); + } + return a; +} + +function mangle_properties(ast, options) { + options = defaults(options, { + cache: null, + debug: false, + ignore_quoted: false, + only_cache: false, + regex: null, + reserved: null, + }); + + var reserved = options.reserved; + if (reserved == null) + reserved = find_builtins(); + + var cache = options.cache; + if (cache == null) { + cache = { + cname: -1, + props: new Dictionary() + }; + } + + var regex = options.regex; + var ignore_quoted = options.ignore_quoted; + + // note debug is either false (disabled), or a string of the debug suffix to use (enabled). + // note debug may be enabled as an empty string, which is falsey. Also treat passing 'true' + // the same as passing an empty string. + var debug = (options.debug !== false); + var debug_name_suffix; + if (debug) { + debug_name_suffix = (options.debug === true ? "" : options.debug); + } + + var names_to_mangle = []; + var unmangleable = []; + var ignored = {}; + + // step 1: find candidates to mangle + ast.walk(new TreeWalker(function(node){ + if (node instanceof AST_ObjectKeyVal) { + add(node.key, ignore_quoted && node.quote); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter, since KeyVal is handled above + add(node.key.name); + } + else if (node instanceof AST_Dot) { + add(node.property); + } + else if (node instanceof AST_Sub) { + addStrings(node.property, ignore_quoted); + } + })); + + // step 2: transform the tree, renaming properties + return ast.transform(new TreeTransformer(function(node){ + if (node instanceof AST_ObjectKeyVal) { + if (!(ignore_quoted && node.quote)) + node.key = mangle(node.key); + } + else if (node instanceof AST_ObjectProperty) { + // setter or getter + node.key.name = mangle(node.key.name); + } + else if (node instanceof AST_Dot) { + node.property = mangle(node.property); + } + else if (node instanceof AST_Sub) { + if (!ignore_quoted) + node.property = mangleStrings(node.property); + } + // else if (node instanceof AST_String) { + // if (should_mangle(node.value)) { + // AST_Node.warn( + // "Found \"{prop}\" property candidate for mangling in an arbitrary string [{file}:{line},{col}]", { + // file : node.start.file, + // line : node.start.line, + // col : node.start.col, + // prop : node.value + // } + // ); + // } + // } + })); + + // only function declarations after this line + + function can_mangle(name) { + if (unmangleable.indexOf(name) >= 0) return false; + if (reserved.indexOf(name) >= 0) return false; + if (options.only_cache) { + return cache.props.has(name); + } + if (/^-?[0-9]+(\.[0-9]+)?(e[+-][0-9]+)?$/.test(name)) return false; + return true; + } + + function should_mangle(name) { + if (ignore_quoted && name in ignored) return false; + if (regex && !regex.test(name)) return false; + if (reserved.indexOf(name) >= 0) return false; + return cache.props.has(name) + || names_to_mangle.indexOf(name) >= 0; + } + + function add(name, ignore) { + if (ignore) { + ignored[name] = true; + return; + } + + if (can_mangle(name)) + push_uniq(names_to_mangle, name); + + if (!should_mangle(name)) { + push_uniq(unmangleable, name); + } + } + + function mangle(name) { + if (!should_mangle(name)) { + return name; + } + + var mangled = cache.props.get(name); + if (!mangled) { + if (debug) { + // debug mode: use a prefix and suffix to preserve readability, e.g. o.foo -> o._$foo$NNN_. + var debug_mangled = "_$" + name + "$" + debug_name_suffix + "_"; + + if (can_mangle(debug_mangled) && !(ignore_quoted && debug_mangled in ignored)) { + mangled = debug_mangled; + } + } + + // either debug mode is off, or it is on and we could not use the mangled name + if (!mangled) { + // note can_mangle() does not check if the name collides with the 'ignored' set + // (filled with quoted properties when ignore_quoted set). Make sure we add this + // check so we don't collide with a quoted name. + do { + mangled = base54(++cache.cname); + } while (!can_mangle(mangled) || (ignore_quoted && mangled in ignored)); + } + + cache.props.set(name, mangled); + } + return mangled; + } + + function addStrings(node, ignore) { + var out = {}; + try { + (function walk(node){ + node.walk(new TreeWalker(function(node){ + if (node instanceof AST_Seq) { + walk(node.cdr); + return true; + } + if (node instanceof AST_String) { + add(node.value, ignore); + return true; + } + if (node instanceof AST_Conditional) { + walk(node.consequent); + walk(node.alternative); + return true; + } + throw out; + })); + })(node); + } catch(ex) { + if (ex !== out) throw ex; + } + } + + function mangleStrings(node) { + return node.transform(new TreeTransformer(function(node){ + if (node instanceof AST_Seq) { + node.cdr = mangleStrings(node.cdr); + } + else if (node instanceof AST_String) { + node.value = mangle(node.value); + } + else if (node instanceof AST_Conditional) { + node.consequent = mangleStrings(node.consequent); + node.alternative = mangleStrings(node.alternative); + } + return node; + })); + } + +} + +exports["Compressor"] = Compressor; +exports["DefaultsError"] = DefaultsError; +exports["Dictionary"] = Dictionary; +exports["JS_Parse_Error"] = JS_Parse_Error; +exports["MAP"] = MAP; +exports["OutputStream"] = OutputStream; +exports["SourceMap"] = SourceMap; +exports["TreeTransformer"] = TreeTransformer; +exports["TreeWalker"] = TreeWalker; +exports["base54"] = base54; +exports["defaults"] = defaults; +exports["mangle_properties"] = mangle_properties; +exports["merge"] = merge; +exports["parse"] = parse; +exports["push_uniq"] = push_uniq; +exports["string_template"] = string_template; +exports["tokenizer"] = tokenizer; +exports["is_identifier"] = is_identifier; +exports["SymbolDef"] = SymbolDef; + +AST_Node.warn_function = function(txt) { logger.error("uglifyjs WARN: " + txt); }; +// workaround for tty output truncation upon process.exit() +[process.stdout, process.stderr].forEach(function(stream){ + if (stream._handle && stream._handle.setBlocking) + stream._handle.setBlocking(true); +}); + +exports.AST_Node.warn_function = function(txt) { + console.error("WARN: %s", txt); +}; + +function read_source_map(code) { + var match = /\n\/\/# sourceMappingURL=data:application\/json(;.*?)?;base64,(.*)/.exec(code); + if (!match) { + exports.AST_Node.warn("inline source map not found"); + return null; + } + return JSON.parse(new Buffer(match[2], "base64")); +} + +exports.minify = function(files, options, name) { + options = exports.defaults(options, { + compress : {}, + fromString : false, + inSourceMap : null, + mangle : {}, + mangleProperties : false, + nameCache : null, + outFileName : null, + output : null, + outSourceMap : null, + parse : {}, + sourceMapInline : false, + sourceMapUrl : null, + sourceRoot : null, + spidermonkey : false, + warnings : false, + }); + exports.base54.reset(); + + var inMap = options.inSourceMap; + if (typeof inMap == "string" && inMap != "inline") { + inMap = JSON.parse(rjsFile.readFile(inMap, "utf8")); + } + + // 1. parse + var toplevel = null, + sourcesContent = {}; + + if (options.spidermonkey) { + if (inMap == "inline") { + throw new Error("inline source map only works with built-in parser"); + } + toplevel = exports.AST_Node.from_mozilla_ast(files); + } else { + var addFile = function(file, fileUrl) { + var code = options.fromString + ? file + : rjsFile.readFile(file, "utf8"); + if (inMap == "inline") { + inMap = read_source_map(code); + } + sourcesContent[fileUrl] = code; + toplevel = exports.parse(code, { + filename: fileUrl, + toplevel: toplevel, + bare_returns: options.parse ? options.parse.bare_returns : undefined + }); + } + if (!options.fromString) { + files = exports.simple_glob(files); + if (inMap == "inline" && files.length > 1) { + throw new Error("inline source map only works with singular input"); + } + } + [].concat(files).forEach(function (files, i) { + if (typeof files === 'string') { + addFile(files, options.fromString ? i : files); + } else { + for (var fileUrl in files) { + addFile(files[fileUrl], fileUrl); + } + } + }); + } + if (options.wrap) { + toplevel = toplevel.wrap_commonjs(options.wrap, options.exportAll); + } + + // 2. compress + if (options.compress) { + var compress = { warnings: options.warnings }; + exports.merge(compress, options.compress); + toplevel.figure_out_scope(options.mangle); + var sq = exports.Compressor(compress); + toplevel = sq.compress(toplevel); + } + + // 3. mangle properties + if (options.mangleProperties || options.nameCache) { + options.mangleProperties.cache = exports.readNameCache(options.nameCache, "props"); + toplevel = exports.mangle_properties(toplevel, options.mangleProperties); + exports.writeNameCache(options.nameCache, "props", options.mangleProperties.cache); + } + + // 4. mangle + if (options.mangle) { + toplevel.figure_out_scope(options.mangle); + toplevel.compute_char_frequency(options.mangle); + toplevel.mangle_names(options.mangle); + } + + // 5. output + var output = { max_line_len: 32000 }; + if (options.outSourceMap || options.sourceMapInline) { + output.source_map = exports.SourceMap({ + // prefer outFileName, otherwise use outSourceMap without .map suffix + file: options.outFileName || (typeof options.outSourceMap === 'string' ? options.outSourceMap.replace(/\.map$/i, '') : null), + orig: inMap, + root: options.sourceRoot + }); + if (options.sourceMapIncludeSources) { + for (var file in sourcesContent) { + if (sourcesContent.hasOwnProperty(file)) { + output.source_map.get().setSourceContent(file, sourcesContent[file]); + } + } + } + + } + if (options.output) { + exports.merge(output, options.output); + } + var stream = exports.OutputStream(output); + toplevel.print(stream); + + + var source_map = output.source_map; + if (source_map) { + source_map = source_map + ""; + } + + var mappingUrlPrefix = "\n//# sourceMappingURL="; + if (options.sourceMapInline) { + stream += mappingUrlPrefix + "data:application/json;charset=utf-8;base64," + new Buffer(source_map).toString("base64"); + } else if (options.outSourceMap && typeof options.outSourceMap === "string" && options.sourceMapUrl !== false) { + stream += mappingUrlPrefix + (typeof options.sourceMapUrl === "string" ? options.sourceMapUrl : options.outSourceMap); + } + + return { + code : stream + "", + map : source_map + }; +}; + +// exports.describe_ast = function() { +// function doitem(ctor) { +// var sub = {}; +// ctor.SUBCLASSES.forEach(function(ctor){ +// sub[ctor.TYPE] = doitem(ctor); +// }); +// var ret = {}; +// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS; +// if (ctor.SUBCLASSES.length > 0) ret.sub = sub; +// return ret; +// } +// return doitem(exports.AST_Node).sub; +// } + +exports.describe_ast = function() { + var out = exports.OutputStream({ beautify: true }); + function doitem(ctor) { + out.print("AST_" + ctor.TYPE); + var props = ctor.SELF_PROPS.filter(function(prop){ + return !/^\$/.test(prop); + }); + if (props.length > 0) { + out.space(); + out.with_parens(function(){ + props.forEach(function(prop, i){ + if (i) out.space(); + out.print(prop); + }); + }); + } + if (ctor.documentation) { + out.space(); + out.print_string(ctor.documentation); + } + if (ctor.SUBCLASSES.length > 0) { + out.space(); + out.with_block(function(){ + ctor.SUBCLASSES.forEach(function(ctor, i){ + out.indent(); + doitem(ctor); + out.newline(); + }); + }); + } + }; + doitem(exports.AST_Node); + return out + ""; +}; + +function readReservedFile(filename, reserved) { + if (!reserved) { + reserved = { vars: [], props: [] }; + } + var data = rjsFile.readFile(filename, "utf8"); + data = JSON.parse(data); + if (data.vars) { + data.vars.forEach(function(name){ + exports.push_uniq(reserved.vars, name); + }); + } + if (data.props) { + data.props.forEach(function(name){ + exports.push_uniq(reserved.props, name); + }); + } + return reserved; +} + +exports.readReservedFile = readReservedFile; + +exports.readDefaultReservedFile = function(reserved) { + return readReservedFile(require.resolve("./domprops.json"), reserved); +}; + +exports.readNameCache = function(filename, key) { + var cache = null; + if (filename) { + try { + var cache = rjsFile.readFile(filename, "utf8"); + cache = JSON.parse(cache)[key]; + if (!cache) throw "init"; + cache.props = exports.Dictionary.fromObject(cache.props); + } catch(ex) { + cache = { + cname: -1, + props: new exports.Dictionary() + }; + } + } + return cache; +}; + +exports.writeNameCache = function(filename, key, cache) { + if (filename) { + var data; + try { + data = rjsFile.readFile(filename, "utf8"); + data = JSON.parse(data); + } catch(ex) { + data = {}; + } + data[key] = { + cname: cache.cname, + props: cache.props.toObject() + }; + rjsFile.writeFile(filename, JSON.stringify(data, null, 2), "utf8"); + } +}; + +// A file glob function that only supports "*" and "?" wildcards in the basename. +// Example: "foo/bar/*baz??.*.js" +// Argument `glob` may be a string or an array of strings. +// Returns an array of strings. Garbage in, garbage out. +exports.simple_glob = function simple_glob(glob) { + if (Array.isArray(glob)) { + return [].concat.apply([], glob.map(simple_glob)); + } + if (glob.match(/\*|\?/)) { + var dir = path.dirname(glob); + try { + var entries = fs.readdirSync(dir); + } catch (ex) {} + if (entries) { + var pattern = "^" + path.basename(glob) + .replace(/[.+^$[\]\\(){}]/g, "\\$&") + .replace(/\*/g, "[^/\\\\]*") + .replace(/\?/g, "[^/\\\\]") + "$"; + var mod = process.platform === "win32" ? "i" : ""; + var rx = new RegExp(pattern, mod); + var results = entries.filter(function(name) { + return rx.test(name); + }).map(function(name) { + return path.join(dir, name); + }); + if (results.length) return results; + } + } + return [ glob ]; +}; + + +}); +/*jslint plusplus: true */ +/*global define: false */ + +define('parse', ['./esprimaAdapter', 'lang'], function (esprima, lang) { + 'use strict'; + + function arrayToString(ary) { + var output = '['; + if (ary) { + ary.forEach(function (item, i) { + output += (i > 0 ? ',' : '') + '"' + lang.jsEscape(item) + '"'; + }); + } + output += ']'; + + return output; + } + + //This string is saved off because JSLint complains + //about obj.arguments use, as 'reserved word' + var argPropName = 'arguments', + //Default object to use for "scope" checking for UMD identifiers. + emptyScope = {}, + mixin = lang.mixin, + hasProp = lang.hasProp; + + //From an esprima example for traversing its ast. + function traverse(object, visitor) { + var child; + + if (!object) { + return; + } + + if (visitor.call(null, object) === false) { + return false; + } + for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[keys[i]]; + if (typeof child === 'object' && child !== null) { + if (traverse(child, visitor) === false) { + return false; + } + } + } + } + + //Like traverse, but visitor returning false just + //stops that subtree analysis, not the rest of tree + //visiting. + function traverseBroad(object, visitor) { + var child; + + if (!object) { + return; + } + + if (visitor.call(null, object) === false) { + return false; + } + for (var i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[key]; + if (typeof child === 'object' && child !== null) { + traverseBroad(child, visitor); + } + } + } + + /** + * Pulls out dependencies from an array literal with just string members. + * If string literals, will just return those string values in an array, + * skipping other items in the array. + * + * @param {Node} node an AST node. + * + * @returns {Array} an array of strings. + * If null is returned, then it means the input node was not a valid + * dependency. + */ + function getValidDeps(node) { + if (!node || node.type !== 'ArrayExpression' || !node.elements) { + return; + } + + var deps = []; + + node.elements.some(function (elem) { + if (elem.type === 'Literal') { + deps.push(elem.value); + } + }); + + return deps.length ? deps : undefined; + } + + // Detects regular or arrow function expressions as the desired expression + // type. + function isFnExpression(node) { + return (node && (node.type === 'FunctionExpression' || + node.type === 'ArrowFunctionExpression')); + } + + /** + * Main parse function. Returns a string of any valid require or + * define/require.def calls as part of one JavaScript source string. + * @param {String} moduleName the module name that represents this file. + * It is used to create a default define if there is not one already for the + * file. This allows properly tracing dependencies for builds. Otherwise, if + * the file just has a require() call, the file dependencies will not be + * properly reflected: the file will come before its dependencies. + * @param {String} moduleName + * @param {String} fileName + * @param {String} fileContents + * @param {Object} options optional options. insertNeedsDefine: true will + * add calls to require.needsDefine() if appropriate. + * @returns {String} JS source string or null, if no require or + * define/require.def calls are found. + */ + function parse(moduleName, fileName, fileContents, options) { + options = options || {}; + + //Set up source input + var i, moduleCall, depString, + moduleDeps = [], + result = '', + moduleList = [], + needsDefine = true, + astRoot = esprima.parse(fileContents); + + parse.recurse(astRoot, function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { + if (!deps) { + deps = []; + } + + if (callName === 'define' && (!name || name === moduleName)) { + needsDefine = false; + } + + if (!name) { + //If there is no module name, the dependencies are for + //this file/default module name. + moduleDeps = moduleDeps.concat(deps); + } else { + moduleList.push({ + name: name, + deps: deps + }); + } + + if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { + return factoryIdentifier; + } + + //If define was found, no need to dive deeper, unless + //the config explicitly wants to dig deeper. + return !!options.findNestedDependencies; + }, options); + + if (options.insertNeedsDefine && needsDefine) { + result += 'require.needsDefine("' + moduleName + '");'; + } + + if (moduleDeps.length || moduleList.length) { + for (i = 0; i < moduleList.length; i++) { + moduleCall = moduleList[i]; + if (result) { + result += '\n'; + } + + //If this is the main module for this file, combine any + //"anonymous" dependencies (could come from a nested require + //call) with this module. + if (moduleCall.name === moduleName) { + moduleCall.deps = moduleCall.deps.concat(moduleDeps); + moduleDeps = []; + } + + depString = arrayToString(moduleCall.deps); + result += 'define("' + moduleCall.name + '",' + + depString + ');'; + } + if (moduleDeps.length) { + if (result) { + result += '\n'; + } + depString = arrayToString(moduleDeps); + result += 'define("' + moduleName + '",' + depString + ');'; + } + } + + return result || null; + } + + parse.traverse = traverse; + parse.traverseBroad = traverseBroad; + parse.isFnExpression = isFnExpression; + + /** + * Handles parsing a file recursively for require calls. + * @param {Array} parentNode the AST node to start with. + * @param {Function} onMatch function to call on a parse match. + * @param {Object} [options] This is normally the build config options if + * it is passed. + * @param {Object} [fnExpScope] holds list of function expresssion + * argument identifiers, set up internally, not passed in + */ + parse.recurse = function (object, onMatch, options, fnExpScope) { + //Like traverse, but skips if branches that would not be processed + //after has application that results in tests of true or false boolean + //literal values. + var keys, child, result, i, params, param, tempObject, + hasHas = options && options.has; + + fnExpScope = fnExpScope || emptyScope; + + if (!object) { + return; + } + + //If has replacement has resulted in if(true){} or if(false){}, take + //the appropriate branch and skip the other one. + if (hasHas && object.type === 'IfStatement' && object.test.type && + object.test.type === 'Literal') { + if (object.test.value) { + //Take the if branch + this.recurse(object.consequent, onMatch, options, fnExpScope); + } else { + //Take the else branch + this.recurse(object.alternate, onMatch, options, fnExpScope); + } + } else { + result = this.parseNode(object, onMatch, fnExpScope); + if (result === false) { + return; + } else if (typeof result === 'string') { + return result; + } + + //Build up a "scope" object that informs nested recurse calls if + //the define call references an identifier that is likely a UMD + //wrapped function expression argument. + //Catch (function(a) {... wrappers + if (object.type === 'ExpressionStatement' && object.expression && + object.expression.type === 'CallExpression' && object.expression.callee && + isFnExpression(object.expression.callee)) { + tempObject = object.expression.callee; + } + // Catch !function(a) {... wrappers + if (object.type === 'UnaryExpression' && object.argument && + object.argument.type === 'CallExpression' && object.argument.callee && + isFnExpression(object.argument.callee)) { + tempObject = object.argument.callee; + } + if (tempObject && tempObject.params && tempObject.params.length) { + params = tempObject.params; + fnExpScope = mixin({}, fnExpScope, true); + for (i = 0; i < params.length; i++) { + param = params[i]; + if (param.type === 'Identifier') { + fnExpScope[param.name] = true; + } + } + } + + for (i = 0, keys = Object.keys(object); i < keys.length; i++) { + child = object[keys[i]]; + if (typeof child === 'object' && child !== null) { + result = this.recurse(child, onMatch, options, fnExpScope); + if (typeof result === 'string' && hasProp(fnExpScope, result)) { + //The result was still in fnExpScope so break. Otherwise, + //was a return from a a tree that had a UMD definition, + //but now out of that scope so keep siblings. + break; + } + } + } + + //Check for an identifier for a factory function identifier being + //passed in as a function expression, indicating a UMD-type of + //wrapping. + if (typeof result === 'string') { + if (hasProp(fnExpScope, result)) { + //result still in scope, keep jumping out indicating the + //identifier still in use. + return result; + } + + return; + } + } + }; + + /** + * Determines if the file defines the require/define module API. + * Specifically, it looks for the `define.amd = ` expression. + * @param {String} fileName + * @param {String} fileContents + * @returns {Boolean} + */ + parse.definesRequire = function (fileName, fileContents) { + var foundDefine = false, + foundDefineAmd = false; + + traverse(esprima.parse(fileContents), function (node) { + // Look for a top level declaration of a define, like + // var requirejs, require, define, off Program body. + if (node.type === 'Program' && node.body && node.body.length) { + foundDefine = node.body.some(function(bodyNode) { + // var define + if (bodyNode.type === 'VariableDeclaration') { + var decls = bodyNode.declarations; + if (decls) { + var hasVarDefine = decls.some(function(declNode) { + return (declNode.type === 'VariableDeclarator' && + declNode.id && + declNode.id.type === 'Identifier' && + declNode.id.name === 'define'); + }); + if (hasVarDefine) { + return true; + } + } + } + + // function define() {} + if (bodyNode.type === 'FunctionDeclaration' && + bodyNode.id && + bodyNode.id.type === 'Identifier' && + bodyNode.id.name === 'define') { + return true; + } + + + + + + + }); + } + + // Need define variable found first, before detecting define.amd. + if (foundDefine && parse.hasDefineAmd(node)) { + foundDefineAmd = true; + + //Stop traversal + return false; + } + }); + + return foundDefine && foundDefineAmd; + }; + + /** + * Finds require("") calls inside a CommonJS anonymous module wrapped in a + * define(function(require, exports, module){}) wrapper. These dependencies + * will be added to a modified define() call that lists the dependencies + * on the outside of the function. + * @param {String} fileName + * @param {String|Object} fileContents: a string of contents, or an already + * parsed AST tree. + * @returns {Array} an array of module names that are dependencies. Always + * returns an array, but could be of length zero. + */ + parse.getAnonDeps = function (fileName, fileContents) { + var astRoot = typeof fileContents === 'string' ? + esprima.parse(fileContents) : fileContents, + defFunc = this.findAnonDefineFactory(astRoot); + + return parse.getAnonDepsFromNode(defFunc); + }; + + /** + * Finds require("") calls inside a CommonJS anonymous module wrapped + * in a define function, given an AST node for the definition function. + * @param {Node} node the AST node for the definition function. + * @returns {Array} and array of dependency names. Can be of zero length. + */ + parse.getAnonDepsFromNode = function (node) { + var deps = [], + funcArgLength; + + if (node) { + this.findRequireDepNames(node, deps); + + //If no deps, still add the standard CommonJS require, exports, + //module, in that order, to the deps, but only if specified as + //function args. In particular, if exports is used, it is favored + //over the return value of the function, so only add it if asked. + funcArgLength = node.params && node.params.length; + if (funcArgLength) { + deps = (funcArgLength > 1 ? ["require", "exports", "module"] : + ["require"]).concat(deps); + } + } + return deps; + }; + + parse.isDefineNodeWithArgs = function (node) { + return node && node.type === 'CallExpression' && + node.callee && node.callee.type === 'Identifier' && + node.callee.name === 'define' && node[argPropName]; + }; + + /** + * Finds the function in define(function (require, exports, module){}); + * @param {Array} node + * @returns {Boolean} + */ + parse.findAnonDefineFactory = function (node) { + var match; + + traverse(node, function (node) { + var arg0, arg1; + + if (parse.isDefineNodeWithArgs(node)) { + + //Just the factory function passed to define + arg0 = node[argPropName][0]; + if (isFnExpression(arg0)) { + match = arg0; + return false; + } + + //A string literal module ID followed by the factory function. + arg1 = node[argPropName][1]; + if (arg0.type === 'Literal' && isFnExpression(arg1)) { + match = arg1; + return false; + } + } + }); + + return match; + }; + + /** + * Finds any config that is passed to requirejs. That includes calls to + * require/requirejs.config(), as well as require({}, ...) and + * requirejs({}, ...) + * @param {String} fileContents + * + * @returns {Object} a config details object with the following properties: + * - config: {Object} the config object found. Can be undefined if no + * config found. + * - range: {Array} the start index and end index in the contents where + * the config was found. Can be undefined if no config found. + * Can throw an error if the config in the file cannot be evaluated in + * a build context to valid JavaScript. + */ + parse.findConfig = function (fileContents) { + /*jslint evil: true */ + var jsConfig, foundConfig, stringData, foundRange, quote, quoteMatch, + quoteRegExp = /(:\s|\[\s*)(['"])/, + astRoot = esprima.parse(fileContents, { + loc: true + }); + + traverse(astRoot, function (node) { + var arg, + requireType = parse.hasRequire(node); + + if (requireType && (requireType === 'require' || + requireType === 'requirejs' || + requireType === 'requireConfig' || + requireType === 'requirejsConfig')) { + + arg = node[argPropName] && node[argPropName][0]; + + if (arg && arg.type === 'ObjectExpression') { + stringData = parse.nodeToString(fileContents, arg); + jsConfig = stringData.value; + foundRange = stringData.range; + return false; + } + } else { + arg = parse.getRequireObjectLiteral(node); + if (arg) { + stringData = parse.nodeToString(fileContents, arg); + jsConfig = stringData.value; + foundRange = stringData.range; + return false; + } + } + }); + + if (jsConfig) { + // Eval the config + quoteMatch = quoteRegExp.exec(jsConfig); + quote = (quoteMatch && quoteMatch[2]) || '"'; + foundConfig = eval('(' + jsConfig + ')'); + } + + return { + config: foundConfig, + range: foundRange, + quote: quote + }; + }; + + /** Returns the node for the object literal assigned to require/requirejs, + * for holding a declarative config. + */ + parse.getRequireObjectLiteral = function (node) { + if (node.id && node.id.type === 'Identifier' && + (node.id.name === 'require' || node.id.name === 'requirejs') && + node.init && node.init.type === 'ObjectExpression') { + return node.init; + } + }; + + /** + * Renames require/requirejs/define calls to be ns + '.' + require/requirejs/define + * Does *not* do .config calls though. See pragma.namespace for the complete + * set of namespace transforms. This function is used because require calls + * inside a define() call should not be renamed, so a simple regexp is not + * good enough. + * @param {String} fileContents the contents to transform. + * @param {String} ns the namespace, *not* including trailing dot. + * @return {String} the fileContents with the namespace applied + */ + parse.renameNamespace = function (fileContents, ns) { + var lines, + locs = [], + astRoot = esprima.parse(fileContents, { + loc: true + }); + + parse.recurse(astRoot, function (callName, config, name, deps, node) { + locs.push(node.loc); + //Do not recurse into define functions, they should be using + //local defines. + return callName !== 'define'; + }, {}); + + if (locs.length) { + lines = fileContents.split('\n'); + + //Go backwards through the found locs, adding in the namespace name + //in front. + locs.reverse(); + locs.forEach(function (loc) { + var startIndex = loc.start.column, + //start.line is 1-based, not 0 based. + lineIndex = loc.start.line - 1, + line = lines[lineIndex]; + + lines[lineIndex] = line.substring(0, startIndex) + + ns + '.' + + line.substring(startIndex, + line.length); + }); + + fileContents = lines.join('\n'); + } + + return fileContents; + }; + + /** + * Finds all dependencies specified in dependency arrays and inside + * simplified commonjs wrappers. + * @param {String} fileName + * @param {String} fileContents + * + * @returns {Array} an array of dependency strings. The dependencies + * have not been normalized, they may be relative IDs. + */ + parse.findDependencies = function (fileName, fileContents, options) { + var dependencies = [], + astRoot = esprima.parse(fileContents); + + parse.recurse(astRoot, function (callName, config, name, deps) { + if (deps) { + dependencies = dependencies.concat(deps); + } + }, options); + + return dependencies; + }; + + /** + * Finds only CJS dependencies, ones that are the form + * require('stringLiteral') + */ + parse.findCjsDependencies = function (fileName, fileContents) { + var dependencies = []; + + traverse(esprima.parse(fileContents), function (node) { + var arg; + + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && node[argPropName] && + node[argPropName].length === 1) { + arg = node[argPropName][0]; + if (arg.type === 'Literal') { + dependencies.push(arg.value); + } + } + }); + + return dependencies; + }; + + //function define() {} + parse.hasDefDefine = function (node) { + return node.type === 'FunctionDeclaration' && node.id && + node.id.type === 'Identifier' && node.id.name === 'define'; + }; + + //define.amd = ... + parse.hasDefineAmd = function (node) { + return node && node.type === 'AssignmentExpression' && + node.left && node.left.type === 'MemberExpression' && + node.left.object && node.left.object.name === 'define' && + node.left.property && node.left.property.name === 'amd'; + }; + + //define.amd reference, as in: if (define.amd) + parse.refsDefineAmd = function (node) { + return node && node.type === 'MemberExpression' && + node.object && node.object.name === 'define' && + node.object.type === 'Identifier' && + node.property && node.property.name === 'amd' && + node.property.type === 'Identifier'; + }; + + //require(), requirejs(), require.config() and requirejs.config() + parse.hasRequire = function (node) { + var callName, + c = node && node.callee; + + if (node && node.type === 'CallExpression' && c) { + if (c.type === 'Identifier' && + (c.name === 'require' || + c.name === 'requirejs')) { + //A require/requirejs({}, ...) call + callName = c.name; + } else if (c.type === 'MemberExpression' && + c.object && + c.object.type === 'Identifier' && + (c.object.name === 'require' || + c.object.name === 'requirejs') && + c.property && c.property.name === 'config') { + // require/requirejs.config({}) call + callName = c.object.name + 'Config'; + } + } + + return callName; + }; + + //define() + parse.hasDefine = function (node) { + return node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'define'; + }; + + /** + * If there is a named define in the file, returns the name. Does not + * scan for mulitple names, just the first one. + */ + parse.getNamedDefine = function (fileContents) { + var name; + traverse(esprima.parse(fileContents), function (node) { + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'define' && + node[argPropName] && node[argPropName][0] && + node[argPropName][0].type === 'Literal') { + name = node[argPropName][0].value; + return false; + } + }); + + return name; + }; + + /** + * Finds all the named define module IDs in a file. + */ + parse.getAllNamedDefines = function (fileContents, excludeMap) { + var names = []; + parse.recurse(esprima.parse(fileContents), + function (callName, config, name, deps, node, factoryIdentifier, fnExpScope) { + if (callName === 'define' && name) { + if (!excludeMap.hasOwnProperty(name)) { + names.push(name); + } + } + + //If a UMD definition that points to a factory that is an Identifier, + //indicate processing should not traverse inside the UMD definition. + if (callName === 'define' && factoryIdentifier && hasProp(fnExpScope, factoryIdentifier)) { + return factoryIdentifier; + } + + //If define was found, no need to dive deeper, unless + //the config explicitly wants to dig deeper. + return true; + }, {}); + + return names; + }; + + /** + * Determines if define(), require({}|[]) or requirejs was called in the + * file. Also finds out if define() is declared and if define.amd is called. + */ + parse.usesAmdOrRequireJs = function (fileName, fileContents) { + var uses; + + traverse(esprima.parse(fileContents), function (node) { + var type, callName, arg; + + if (parse.hasDefDefine(node)) { + //function define() {} + type = 'declaresDefine'; + } else if (parse.hasDefineAmd(node)) { + type = 'defineAmd'; + } else { + callName = parse.hasRequire(node); + if (callName) { + arg = node[argPropName] && node[argPropName][0]; + if (arg && (arg.type === 'ObjectExpression' || + arg.type === 'ArrayExpression')) { + type = callName; + } + } else if (parse.hasDefine(node)) { + type = 'define'; + } + } + + if (type) { + if (!uses) { + uses = {}; + } + uses[type] = true; + } + }); + + return uses; + }; + + /** + * Determines if require(''), exports.x =, module.exports =, + * __dirname, __filename are used. So, not strictly traditional CommonJS, + * also checks for Node variants. + */ + parse.usesCommonJs = function (fileName, fileContents) { + var uses = null, + assignsExports = false; + + + traverse(esprima.parse(fileContents), function (node) { + var type, + exp = node.expression || node.init; + + if (node.type === 'Identifier' && + (node.name === '__dirname' || node.name === '__filename')) { + type = node.name.substring(2); + } else if (node.type === 'VariableDeclarator' && node.id && + node.id.type === 'Identifier' && + node.id.name === 'exports') { + //Hmm, a variable assignment for exports, so does not use cjs + //exports. + type = 'varExports'; + } else if (exp && exp.type === 'AssignmentExpression' && exp.left && + exp.left.type === 'MemberExpression' && exp.left.object) { + if (exp.left.object.name === 'module' && exp.left.property && + exp.left.property.name === 'exports') { + type = 'moduleExports'; + } else if (exp.left.object.name === 'exports' && + exp.left.property) { + type = 'exports'; + } else if (exp.left.object.type === 'MemberExpression' && + exp.left.object.object.name === 'module' && + exp.left.object.property.name === 'exports' && + exp.left.object.property.type === 'Identifier') { + type = 'moduleExports'; + } + + } else if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && node[argPropName] && + node[argPropName].length === 1 && + node[argPropName][0].type === 'Literal') { + type = 'require'; + } + + if (type) { + if (type === 'varExports') { + assignsExports = true; + } else if (type !== 'exports' || !assignsExports) { + if (!uses) { + uses = {}; + } + uses[type] = true; + } + } + }); + + return uses; + }; + + + parse.findRequireDepNames = function (node, deps) { + traverse(node, function (node) { + var arg; + + if (node && node.type === 'CallExpression' && node.callee && + node.callee.type === 'Identifier' && + node.callee.name === 'require' && + node[argPropName] && node[argPropName].length === 1) { + + arg = node[argPropName][0]; + if (arg.type === 'Literal') { + deps.push(arg.value); + } + } + }); + }; + + /** + * Determines if a specific node is a valid require or define/require.def + * call. + * @param {Array} node + * @param {Function} onMatch a function to call when a match is found. + * It is passed the match name, and the config, name, deps possible args. + * The config, name and deps args are not normalized. + * @param {Object} fnExpScope an object whose keys are all function + * expression identifiers that should be in scope. Useful for UMD wrapper + * detection to avoid parsing more into the wrapped UMD code. + * + * @returns {String} a JS source string with the valid require/define call. + * Otherwise null. + */ + parse.parseNode = function (node, onMatch, fnExpScope) { + var name, deps, cjsDeps, arg, factory, exp, refsDefine, bodyNode, + args = node && node[argPropName], + callName = parse.hasRequire(node), + isUmd = false; + + if (callName === 'require' || callName === 'requirejs') { + //A plain require/requirejs call + arg = node[argPropName] && node[argPropName][0]; + if (arg && arg.type !== 'ArrayExpression') { + if (arg.type === 'ObjectExpression') { + //A config call, try the second arg. + arg = node[argPropName][1]; + } + } + + deps = getValidDeps(arg); + if (!deps) { + return; + } + + return onMatch("require", null, null, deps, node); + } else if (parse.hasDefine(node) && args && args.length) { + name = args[0]; + deps = args[1]; + factory = args[2]; + + if (name.type === 'ArrayExpression') { + //No name, adjust args + factory = deps; + deps = name; + name = null; + } else if (isFnExpression(name)) { + //Just the factory, no name or deps + factory = name; + name = deps = null; + } else if (name.type === 'Identifier' && args.length === 1 && + hasProp(fnExpScope, name.name)) { + //define(e) where e is a UMD identifier for the factory + //function. + isUmd = true; + factory = name; + name = null; + } else if (name.type !== 'Literal') { + //An object literal, just null out + name = deps = factory = null; + } + + if (name && name.type === 'Literal' && deps) { + if (isFnExpression(deps)) { + //deps is the factory + factory = deps; + deps = null; + } else if (deps.type === 'ObjectExpression') { + //deps is object literal, null out + deps = factory = null; + } else if (deps.type === 'Identifier') { + if (args.length === 2) { + //define('id', factory) + deps = factory = null; + } else if (args.length === 3 && isFnExpression(factory)) { + //define('id', depsIdentifier, factory) + //Since identifier, cannot know the deps, but do not + //error out, assume they are taken care of outside of + //static parsing. + deps = null; + } + } + } + + if (deps && deps.type === 'ArrayExpression') { + deps = getValidDeps(deps); + } else if (isFnExpression(factory)) { + //If no deps and a factory function, could be a commonjs sugar + //wrapper, scan the function for dependencies. + cjsDeps = parse.getAnonDepsFromNode(factory); + if (cjsDeps.length) { + deps = cjsDeps; + } + } else if (deps || (factory && !isUmd)) { + //Does not match the shape of an AMD call. + return; + } + + //Just save off the name as a string instead of an AST object. + if (name && name.type === 'Literal') { + name = name.value; + } + + return onMatch("define", null, name, deps, node, + (factory && factory.type === 'Identifier' ? factory.name : undefined), + fnExpScope); + } else if (node.type === 'CallExpression' && node.callee && + isFnExpression(node.callee) && + node.callee.body && node.callee.body.body && + node.callee.body.body.length === 1 && + node.callee.body.body[0].type === 'IfStatement') { + bodyNode = node.callee.body.body[0]; + //Look for a define(Identifier) case, but only if inside an + //if that has a define.amd test + if (bodyNode.consequent && bodyNode.consequent.body) { + exp = bodyNode.consequent.body[0]; + if (exp.type === 'ExpressionStatement' && exp.expression && + parse.hasDefine(exp.expression) && + exp.expression.arguments && + exp.expression.arguments.length === 1 && + exp.expression.arguments[0].type === 'Identifier') { + + //Calls define(Identifier) as first statement in body. + //Confirm the if test references define.amd + traverse(bodyNode.test, function (node) { + if (parse.refsDefineAmd(node)) { + refsDefine = true; + return false; + } + }); + + if (refsDefine) { + return onMatch("define", null, null, null, exp.expression, + exp.expression.arguments[0].name, fnExpScope); + } + } + } + } + }; + + /** + * Converts an AST node into a JS source string by extracting + * the node's location from the given contents string. Assumes + * esprima.parse() with loc was done. + * @param {String} contents + * @param {Object} node + * @returns {String} a JS source string. + */ + parse.nodeToString = function (contents, node) { + var extracted, + loc = node.loc, + lines = contents.split('\n'), + firstLine = loc.start.line > 1 ? + lines.slice(0, loc.start.line - 1).join('\n') + '\n' : + '', + preamble = firstLine + + lines[loc.start.line - 1].substring(0, loc.start.column); + + if (loc.start.line === loc.end.line) { + extracted = lines[loc.start.line - 1].substring(loc.start.column, + loc.end.column); + } else { + extracted = lines[loc.start.line - 1].substring(loc.start.column) + + '\n' + + lines.slice(loc.start.line, loc.end.line - 1).join('\n') + + '\n' + + lines[loc.end.line - 1].substring(0, loc.end.column); + } + + return { + value: extracted, + range: [ + preamble.length, + preamble.length + extracted.length + ] + }; + }; + + /** + * Extracts license comments from JS text. + * @param {String} fileName + * @param {String} contents + * @returns {String} a string of license comments. + */ + parse.getLicenseComments = function (fileName, contents) { + var commentNode, refNode, subNode, value, i, j, + //xpconnect's Reflect does not support comment or range, but + //prefer continued operation vs strict parity of operation, + //as license comments can be expressed in other ways, like + //via wrap args, or linked via sourcemaps. + ast = esprima.parse(contents, { + comment: true, + range: true + }), + result = '', + existsMap = {}, + lineEnd = contents.indexOf('\r') === -1 ? '\n' : '\r\n'; + + if (ast.comments) { + for (i = 0; i < ast.comments.length; i++) { + commentNode = ast.comments[i]; + + if (commentNode.type === 'Line') { + value = '//' + commentNode.value + lineEnd; + refNode = commentNode; + + if (i + 1 >= ast.comments.length) { + value += lineEnd; + } else { + //Look for immediately adjacent single line comments + //since it could from a multiple line comment made out + //of single line comments. Like this comment. + for (j = i + 1; j < ast.comments.length; j++) { + subNode = ast.comments[j]; + if (subNode.type === 'Line' && + subNode.range[0] === refNode.range[1] + 1) { + //Adjacent single line comment. Collect it. + value += '//' + subNode.value + lineEnd; + refNode = subNode; + } else { + //No more single line comment blocks. Break out + //and continue outer looping. + break; + } + } + value += lineEnd; + i = j - 1; + } + } else { + value = '/*' + commentNode.value + '*/' + lineEnd + lineEnd; + } + + if (!existsMap[value] && (value.indexOf('license') !== -1 || + (commentNode.type === 'Block' && + value.indexOf('/*!') === 0) || + value.indexOf('opyright') !== -1 || + value.indexOf('(c)') !== -1)) { + + result += value; + existsMap[value] = true; + } + + } + } + + return result; + }; + + return parse; +}); +/*global define */ + +define('transform', [ './esprimaAdapter', './parse', 'logger', 'lang'], +function (esprima, parse, logger, lang) { + 'use strict'; + var transform, + baseIndentRegExp = /^([ \t]+)/, + indentRegExp = /\{[\r\n]+([ \t]+)/, + keyRegExp = /^[_A-Za-z]([A-Za-z\d_]*)$/, + bulkIndentRegExps = { + '\n': /\n/g, + '\r\n': /\r\n/g + }; + + function applyIndent(str, indent, lineReturn) { + var regExp = bulkIndentRegExps[lineReturn]; + return str.replace(regExp, '$&' + indent); + } + + transform = { + toTransport: function (namespace, moduleName, path, contents, onFound, options) { + options = options || {}; + + var astRoot, contentLines, modLine, + foundAnon, + scanCount = 0, + scanReset = false, + defineInfos = [], + applySourceUrl = function (contents) { + if (options.useSourceUrl) { + contents = 'eval("' + lang.jsEscape(contents) + + '\\n//# sourceURL=' + (path.indexOf('/') === 0 ? '' : '/') + + path + + '");\n'; + } + return contents; + }; + + try { + astRoot = esprima.parse(contents, { + loc: true + }); + } catch (e) { + logger.trace('toTransport skipping ' + path + ': ' + + e.toString()); + return contents; + } + + //Find the define calls and their position in the files. + parse.traverse(astRoot, function (node) { + var args, firstArg, firstArgLoc, factoryNode, + needsId, depAction, foundId, init, + sourceUrlData, range, + namespaceExists = false; + + // If a bundle script with a define declaration, do not + // parse any further at this level. Likely a built layer + // by some other tool. + if (node.type === 'VariableDeclarator' && + node.id && node.id.name === 'define' && + node.id.type === 'Identifier') { + init = node.init; + if (init && init.callee && + init.callee.type === 'CallExpression' && + init.callee.callee && + init.callee.callee.type === 'Identifier' && + init.callee.callee.name === 'require' && + init.callee.arguments && init.callee.arguments.length === 1 && + init.callee.arguments[0].type === 'Literal' && + init.callee.arguments[0].value && + init.callee.arguments[0].value.indexOf('amdefine') !== -1) { + // the var define = require('amdefine')(module) case, + // keep going in that case. + } else { + return false; + } + } + + namespaceExists = namespace && + node.type === 'CallExpression' && + node.callee && node.callee.object && + node.callee.object.type === 'Identifier' && + node.callee.object.name === namespace && + node.callee.property.type === 'Identifier' && + node.callee.property.name === 'define'; + + if (namespaceExists || parse.isDefineNodeWithArgs(node)) { + //The arguments are where its at. + args = node.arguments; + if (!args || !args.length) { + return; + } + + firstArg = args[0]; + firstArgLoc = firstArg.loc; + + if (args.length === 1) { + if (firstArg.type === 'Identifier') { + //The define(factory) case, but + //only allow it if one Identifier arg, + //to limit impact of false positives. + needsId = true; + depAction = 'empty'; + } else if (parse.isFnExpression(firstArg)) { + //define(function(){}) + factoryNode = firstArg; + needsId = true; + depAction = 'scan'; + } else if (firstArg.type === 'ObjectExpression') { + //define({}); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'Literal' && + typeof firstArg.value === 'number') { + //define('12345'); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'UnaryExpression' && + firstArg.operator === '-' && + firstArg.argument && + firstArg.argument.type === 'Literal' && + typeof firstArg.argument.value === 'number') { + //define('-12345'); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'MemberExpression' && + firstArg.object && + firstArg.property && + firstArg.property.type === 'Identifier') { + //define(this.key); + needsId = true; + depAction = 'empty'; + } + } else if (firstArg.type === 'ArrayExpression') { + //define([], ...); + needsId = true; + depAction = 'skip'; + } else if (firstArg.type === 'Literal' && + typeof firstArg.value === 'string') { + //define('string', ....) + //Already has an ID. + needsId = false; + if (args.length === 2 && + parse.isFnExpression(args[1])) { + //Needs dependency scanning. + factoryNode = args[1]; + depAction = 'scan'; + } else { + depAction = 'skip'; + } + } else { + //Unknown define entity, keep looking, even + //in the subtree for this node. + return; + } + + range = { + foundId: foundId, + needsId: needsId, + depAction: depAction, + namespaceExists: namespaceExists, + node: node, + defineLoc: node.loc, + firstArgLoc: firstArgLoc, + factoryNode: factoryNode, + sourceUrlData: sourceUrlData + }; + + //Only transform ones that do not have IDs. If it has an + //ID but no dependency array, assume it is something like + //a phonegap implementation, that has its own internal + //define that cannot handle dependency array constructs, + //and if it is a named module, then it means it has been + //set for transport form. + if (range.needsId) { + if (foundAnon) { + logger.trace(path + ' has more than one anonymous ' + + 'define. May be a built file from another ' + + 'build system like, Ender. Skipping normalization.'); + defineInfos = []; + return false; + } else { + foundAnon = range; + defineInfos.push(range); + } + } else if (depAction === 'scan') { + scanCount += 1; + if (scanCount > 1) { + //Just go back to an array that just has the + //anon one, since this is an already optimized + //file like the phonegap one. + if (!scanReset) { + defineInfos = foundAnon ? [foundAnon] : []; + scanReset = true; + } + } else { + defineInfos.push(range); + } + } + } + }); + + + if (!defineInfos.length) { + return applySourceUrl(contents); + } + + //Reverse the matches, need to start from the bottom of + //the file to modify it, so that the ranges are still true + //further up. + defineInfos.reverse(); + + contentLines = contents.split('\n'); + + modLine = function (loc, contentInsertion) { + var startIndex = loc.start.column, + //start.line is 1-based, not 0 based. + lineIndex = loc.start.line - 1, + line = contentLines[lineIndex]; + contentLines[lineIndex] = line.substring(0, startIndex) + + contentInsertion + + line.substring(startIndex, + line.length); + }; + + defineInfos.forEach(function (info) { + var deps, + contentInsertion = '', + depString = ''; + + //Do the modifications "backwards", in other words, start with the + //one that is farthest down and work up, so that the ranges in the + //defineInfos still apply. So that means deps, id, then namespace. + if (info.needsId && moduleName) { + contentInsertion += "'" + moduleName + "',"; + } + + if (info.depAction === 'scan') { + deps = parse.getAnonDepsFromNode(info.factoryNode); + + if (deps.length) { + depString = '[' + deps.map(function (dep) { + return "'" + dep + "'"; + }) + ']'; + } else { + depString = '[]'; + } + depString += ','; + + if (info.factoryNode) { + //Already have a named module, need to insert the + //dependencies after the name. + modLine(info.factoryNode.loc, depString); + } else { + contentInsertion += depString; + } + } + + if (contentInsertion) { + modLine(info.firstArgLoc, contentInsertion); + } + + //Do namespace last so that ui does not mess upthe parenRange + //used above. + if (namespace && !info.namespaceExists) { + modLine(info.defineLoc, namespace + '.'); + } + + //Notify any listener for the found info + if (onFound) { + onFound(info); + } + }); + + contents = contentLines.join('\n'); + + return applySourceUrl(contents); + }, + + /** + * Modify the contents of a require.config/requirejs.config call. This + * call will LOSE any existing comments that are in the config string. + * + * @param {String} fileContents String that may contain a config call + * @param {Function} onConfig Function called when the first config + * call is found. It will be passed an Object which is the current + * config, and the onConfig function should return an Object to use + * as the config. + * @return {String} the fileContents with the config changes applied. + */ + modifyConfig: function (fileContents, onConfig) { + var details = parse.findConfig(fileContents), + config = details.config; + + if (config) { + config = onConfig(config); + if (config) { + return transform.serializeConfig(config, + fileContents, + details.range[0], + details.range[1], + { + quote: details.quote + }); + } + } + + return fileContents; + }, + + serializeConfig: function (config, fileContents, start, end, options) { + //Calculate base level of indent + var indent, match, configString, outDentRegExp, + baseIndent = '', + startString = fileContents.substring(0, start), + existingConfigString = fileContents.substring(start, end), + lineReturn = existingConfigString.indexOf('\r') === -1 ? '\n' : '\r\n', + lastReturnIndex = startString.lastIndexOf('\n'); + + //Get the basic amount of indent for the require config call. + if (lastReturnIndex === -1) { + lastReturnIndex = 0; + } + + match = baseIndentRegExp.exec(startString.substring(lastReturnIndex + 1, start)); + if (match && match[1]) { + baseIndent = match[1]; + } + + //Calculate internal indentation for config + match = indentRegExp.exec(existingConfigString); + if (match && match[1]) { + indent = match[1]; + } + + if (!indent || indent.length < baseIndent) { + indent = ' '; + } else { + indent = indent.substring(baseIndent.length); + } + + outDentRegExp = new RegExp('(' + lineReturn + ')' + indent, 'g'); + + configString = transform.objectToString(config, { + indent: indent, + lineReturn: lineReturn, + outDentRegExp: outDentRegExp, + quote: options && options.quote + }); + + //Add in the base indenting level. + configString = applyIndent(configString, baseIndent, lineReturn); + + return startString + configString + fileContents.substring(end); + }, + + /** + * Tries converting a JS object to a string. This will likely suck, and + * is tailored to the type of config expected in a loader config call. + * So, hasOwnProperty fields, strings, numbers, arrays and functions, + * no weird recursively referenced stuff. + * @param {Object} obj the object to convert + * @param {Object} options options object with the following values: + * {String} indent the indentation to use for each level + * {String} lineReturn the type of line return to use + * {outDentRegExp} outDentRegExp the regexp to use to outdent functions + * {String} quote the quote type to use, ' or ". Optional. Default is " + * @param {String} totalIndent the total indent to print for this level + * @return {String} a string representation of the object. + */ + objectToString: function (obj, options, totalIndent) { + var startBrace, endBrace, nextIndent, + first = true, + value = '', + lineReturn = options.lineReturn, + indent = options.indent, + outDentRegExp = options.outDentRegExp, + quote = options.quote || '"'; + + totalIndent = totalIndent || ''; + nextIndent = totalIndent + indent; + + if (obj === null) { + value = 'null'; + } else if (obj === undefined) { + value = 'undefined'; + } else if (typeof obj === 'number' || typeof obj === 'boolean') { + value = obj; + } else if (typeof obj === 'string') { + //Use double quotes in case the config may also work as JSON. + value = quote + lang.jsEscape(obj) + quote; + } else if (lang.isArray(obj)) { + lang.each(obj, function (item, i) { + value += (i !== 0 ? ',' + lineReturn : '' ) + + nextIndent + + transform.objectToString(item, + options, + nextIndent); + }); + + startBrace = '['; + endBrace = ']'; + } else if (lang.isFunction(obj) || lang.isRegExp(obj)) { + //The outdent regexp just helps pretty up the conversion + //just in node. Rhino strips comments and does a different + //indent scheme for Function toString, so not really helpful + //there. + value = obj.toString().replace(outDentRegExp, '$1'); + } else { + //An object + lang.eachProp(obj, function (v, prop) { + value += (first ? '': ',' + lineReturn) + + nextIndent + + (keyRegExp.test(prop) ? prop : quote + lang.jsEscape(prop) + quote )+ + ': ' + + transform.objectToString(v, + options, + nextIndent); + first = false; + }); + startBrace = '{'; + endBrace = '}'; + } + + if (startBrace) { + value = startBrace + + lineReturn + + value + + lineReturn + totalIndent + + endBrace; + } + + return value; + } + }; + + return transform; +}); +/*jslint regexp: true, plusplus: true */ +/*global define: false */ + +define('pragma', ['parse', 'logger'], function (parse, logger) { + 'use strict'; + function Temp() {} + + function create(obj, mixin) { + Temp.prototype = obj; + var temp = new Temp(), prop; + + //Avoid any extra memory hanging around + Temp.prototype = null; + + if (mixin) { + for (prop in mixin) { + if (mixin.hasOwnProperty(prop) && !temp.hasOwnProperty(prop)) { + temp[prop] = mixin[prop]; + } + } + } + + return temp; // Object + } + + var pragma = { + conditionalRegExp: /(exclude|include)Start\s*\(\s*["'](\w+)["']\s*,(.*)\)/, + useStrictRegExp: /(^|[^{]\r?\n)['"]use strict['"];/g, + hasRegExp: /has\s*\(\s*['"]([^'"]+)['"]\s*\)/g, + configRegExp: /(^|[^\.])(requirejs|require)(\.config)\s*\(/g, + nsWrapRegExp: /\/\*requirejs namespace: true \*\//, + apiDefRegExp: /var requirejs,\s*require,\s*define;/, + defineCheckRegExp: /typeof(\s+|\s*\(\s*)define(\s*\))?\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd/g, + defineStringCheckRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\[\s*["']amd["']\s*\]/g, + defineTypeFirstCheckRegExp: /\s*["']function["']\s*==(=?)\s*typeof\s+define\s*&&\s*define\s*\.\s*amd/g, + defineJQueryRegExp: /typeof\s+define\s*===?\s*["']function["']\s*&&\s*define\s*\.\s*amd\s*&&\s*define\s*\.\s*amd\s*\.\s*jQuery/g, + defineHasRegExp: /typeof\s+define\s*==(=)?\s*['"]function['"]\s*&&\s*typeof\s+define\.amd\s*==(=)?\s*['"]object['"]\s*&&\s*define\.amd/g, + defineTernaryRegExp: /typeof\s+define\s*===?\s*['"]function["']\s*&&\s*define\s*\.\s*amd\s*\?\s*define/, + defineExistsRegExp: /\s+typeof\s+define\s*!==?\s*['"]undefined["']\s*/, + defineExistsAndAmdRegExp: /typeof\s+define\s*!==?\s*['"]undefined["']\s*&&\s*define\s*\.\s*amd\s*/, + amdefineRegExp: /if\s*\(\s*typeof define\s*\!==\s*['"]function['"]\s*\)\s*\{\s*[^\{\}]+amdefine[^\{\}]+\}/g, + + removeStrict: function (contents, config) { + return config.useStrict ? contents : contents.replace(pragma.useStrictRegExp, '$1'); + }, + + namespace: function (fileContents, ns, onLifecycleName) { + if (ns) { + //Namespace require/define calls + fileContents = fileContents.replace(pragma.configRegExp, '$1' + ns + '.$2$3('); + + + fileContents = parse.renameNamespace(fileContents, ns); + + //Namespace define ternary use: + fileContents = fileContents.replace(pragma.defineTernaryRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd ? " + ns + ".define"); + + //Namespace define jquery use: + fileContents = fileContents.replace(pragma.defineJQueryRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd && " + ns + ".define.amd.jQuery"); + + //Namespace has.js define use: + fileContents = fileContents.replace(pragma.defineHasRegExp, + "typeof " + ns + ".define === 'function' && typeof " + ns + ".define.amd === 'object' && " + ns + ".define.amd"); + + //Namespace async.js define use: + fileContents = fileContents.replace(pragma.defineExistsAndAmdRegExp, + "typeof " + ns + ".define !== 'undefined' && " + ns + ".define.amd"); + + //Namespace define checks. + //Do these ones last, since they are a subset of the more specific + //checks above. + fileContents = fileContents.replace(pragma.defineCheckRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define.amd"); + fileContents = fileContents.replace(pragma.defineStringCheckRegExp, + "typeof " + ns + ".define === 'function' && " + ns + ".define['amd']"); + fileContents = fileContents.replace(pragma.defineTypeFirstCheckRegExp, + "'function' === typeof " + ns + ".define && " + ns + ".define.amd"); + fileContents = fileContents.replace(pragma.defineExistsRegExp, + "typeof " + ns + ".define !== 'undefined'"); + + //Check for require.js with the require/define definitions + if (pragma.apiDefRegExp.test(fileContents) && + fileContents.indexOf("if (!" + ns + " || !" + ns + ".requirejs)") === -1) { + //Wrap the file contents in a typeof check, and a function + //to contain the API globals. + fileContents = "var " + ns + ";(function () { if (!" + ns + " || !" + ns + ".requirejs) {\n" + + "if (!" + ns + ") { " + ns + ' = {}; } else { require = ' + ns + '; }\n' + + fileContents + + "\n" + + ns + ".requirejs = requirejs;" + + ns + ".require = require;" + + ns + ".define = define;\n" + + "}\n}());"; + } + + //Finally, if the file wants a special wrapper because it ties + //in to the requirejs internals in a way that would not fit + //the above matches, do that. Look for /*requirejs namespace: true*/ + if (pragma.nsWrapRegExp.test(fileContents)) { + //Remove the pragma. + fileContents = fileContents.replace(pragma.nsWrapRegExp, ''); + + //Alter the contents. + fileContents = '(function () {\n' + + 'var require = ' + ns + '.require,' + + 'requirejs = ' + ns + '.requirejs,' + + 'define = ' + ns + '.define;\n' + + fileContents + + '\n}());'; + } + } + + return fileContents; + }, + + /** + * processes the fileContents for some //>> conditional statements + */ + process: function (fileName, fileContents, config, onLifecycleName, pluginCollector) { + /*jslint evil: true */ + var foundIndex = -1, startIndex = 0, lineEndIndex, conditionLine, + matches, type, marker, condition, isTrue, endRegExp, endMatches, + endMarkerIndex, shouldInclude, startLength, lifecycleHas, deps, + i, dep, moduleName, collectorMod, + lifecyclePragmas, pragmas = config.pragmas, hasConfig = config.has, + //Legacy arg defined to help in dojo conversion script. Remove later + //when dojo no longer needs conversion: + kwArgs = pragmas; + + //Mix in a specific lifecycle scoped object, to allow targeting + //some pragmas/has tests to only when files are saved, or at different + //lifecycle events. Do not bother with kwArgs in this section, since + //the old dojo kwArgs were for all points in the build lifecycle. + if (onLifecycleName) { + lifecyclePragmas = config['pragmas' + onLifecycleName]; + lifecycleHas = config['has' + onLifecycleName]; + + if (lifecyclePragmas) { + pragmas = create(pragmas || {}, lifecyclePragmas); + } + + if (lifecycleHas) { + hasConfig = create(hasConfig || {}, lifecycleHas); + } + } + + //Replace has references if desired + if (hasConfig) { + fileContents = fileContents.replace(pragma.hasRegExp, function (match, test) { + if (hasConfig.hasOwnProperty(test)) { + return !!hasConfig[test]; + } + return match; + }); + } + + if (!config.skipPragmas) { + + while ((foundIndex = fileContents.indexOf("//>>", startIndex)) !== -1) { + //Found a conditional. Get the conditional line. + lineEndIndex = fileContents.indexOf("\n", foundIndex); + if (lineEndIndex === -1) { + lineEndIndex = fileContents.length - 1; + } + + //Increment startIndex past the line so the next conditional search can be done. + startIndex = lineEndIndex + 1; + + //Break apart the conditional. + conditionLine = fileContents.substring(foundIndex, lineEndIndex + 1); + matches = conditionLine.match(pragma.conditionalRegExp); + if (matches) { + type = matches[1]; + marker = matches[2]; + condition = matches[3]; + isTrue = false; + //See if the condition is true. + try { + isTrue = !!eval("(" + condition + ")"); + } catch (e) { + throw "Error in file: " + + fileName + + ". Conditional comment: " + + conditionLine + + " failed with this error: " + e; + } + + //Find the endpoint marker. + endRegExp = new RegExp('\\/\\/\\>\\>\\s*' + type + 'End\\(\\s*[\'"]' + marker + '[\'"]\\s*\\)', "g"); + endMatches = endRegExp.exec(fileContents.substring(startIndex, fileContents.length)); + if (endMatches) { + endMarkerIndex = startIndex + endRegExp.lastIndex - endMatches[0].length; + + //Find the next line return based on the match position. + lineEndIndex = fileContents.indexOf("\n", endMarkerIndex); + if (lineEndIndex === -1) { + lineEndIndex = fileContents.length - 1; + } + + //Should we include the segment? + shouldInclude = ((type === "exclude" && !isTrue) || (type === "include" && isTrue)); + + //Remove the conditional comments, and optionally remove the content inside + //the conditional comments. + startLength = startIndex - foundIndex; + fileContents = fileContents.substring(0, foundIndex) + + (shouldInclude ? fileContents.substring(startIndex, endMarkerIndex) : "") + + fileContents.substring(lineEndIndex + 1, fileContents.length); + + //Move startIndex to foundIndex, since that is the new position in the file + //where we need to look for more conditionals in the next while loop pass. + startIndex = foundIndex; + } else { + throw "Error in file: " + + fileName + + ". Cannot find end marker for conditional comment: " + + conditionLine; + + } + } + } + } + + //If need to find all plugin resources to optimize, do that now, + //before namespacing, since the namespacing will change the API + //names. + //If there is a plugin collector, scan the file for plugin resources. + if (config.optimizeAllPluginResources && pluginCollector) { + try { + deps = parse.findDependencies(fileName, fileContents); + if (deps.length) { + for (i = 0; i < deps.length; i++) { + dep = deps[i]; + if (dep.indexOf('!') !== -1) { + moduleName = dep.split('!')[0]; + collectorMod = pluginCollector[moduleName]; + if (!collectorMod) { + collectorMod = pluginCollector[moduleName] = []; + } + collectorMod.push(dep); + } + } + } + } catch (eDep) { + logger.error('Parse error looking for plugin resources in ' + + fileName + ', skipping.'); + } + } + + //Strip amdefine use for node-shared modules. + if (!config.keepAmdefine) { + fileContents = fileContents.replace(pragma.amdefineRegExp, ''); + } + + //Do namespacing + if (onLifecycleName === 'OnSave' && config.namespace) { + fileContents = pragma.namespace(fileContents, config.namespace, onLifecycleName); + } + + + return pragma.removeStrict(fileContents, config); + } + }; + + return pragma; +}); + +if(env === 'browser') { +/*jslint strict: false */ +/*global define: false */ + +define('browser/optimize', {}); + +} + +if(env === 'node') { +/*jslint strict: false */ +/*global define: false */ + +define('node/optimize', {}); + +} + +if(env === 'rhino') { +/*jslint sloppy: true, plusplus: true */ +/*global define, java, Packages, com */ + +define('rhino/optimize', ['logger', 'env!env/file'], function (logger, file) { + + //Add .reduce to Rhino so UglifyJS can run in Rhino, + //inspired by https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/reduce + //but rewritten for brevity, and to be good enough for use by UglifyJS. + if (!Array.prototype.reduce) { + Array.prototype.reduce = function (fn /*, initialValue */) { + var i = 0, + length = this.length, + accumulator; + + if (arguments.length >= 2) { + accumulator = arguments[1]; + } else { + if (length) { + while (!(i in this)) { + i++; + } + accumulator = this[i++]; + } + } + + for (; i < length; i++) { + if (i in this) { + accumulator = fn.call(undefined, accumulator, this[i], i, this); + } + } + + return accumulator; + }; + } + + var JSSourceFilefromCode, optimize, + mapRegExp = /"file":"[^"]+"/; + + //Bind to Closure compiler, but if it is not available, do not sweat it. + try { + // Try older closure compiler that worked on Java 6 + JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.JSSourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); + } catch (e) { + try { + // Try for newer closure compiler that needs Java 7+ + JSSourceFilefromCode = java.lang.Class.forName('com.google.javascript.jscomp.SourceFile').getMethod('fromCode', [java.lang.String, java.lang.String]); + } catch (e) { + try { + // Try Nashorn style + var stringClass = Java.type("java.lang.String").class; + JSSourceFilefromCode = Java.type("com.google.javascript.jscomp.SourceFile").class.getMethod("fromCode", [stringClass, stringClass]); + } catch (e) {} + } + } + + //Helper for closure compiler, because of weird Java-JavaScript interactions. + function closurefromCode(filename, content) { + return JSSourceFilefromCode.invoke(null, [filename, content]); + } + + + function getFileWriter(fileName, encoding) { + var outFile = new java.io.File(fileName), outWriter, parentDir; + + parentDir = outFile.getAbsoluteFile().getParentFile(); + if (!parentDir.exists()) { + if (!parentDir.mkdirs()) { + throw "Could not create directory: " + parentDir.getAbsolutePath(); + } + } + + if (encoding) { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile), encoding); + } else { + outWriter = new java.io.OutputStreamWriter(new java.io.FileOutputStream(outFile)); + } + + return new java.io.BufferedWriter(outWriter); + } + + optimize = { + closure: function (fileName, fileContents, outFileName, keepLines, config) { + config = config || {}; + var result, mappings, optimized, compressed, baseName, writer, + outBaseName, outFileNameMap, outFileNameMapContent, + srcOutFileName, concatNameMap, + jscomp = Packages.com.google.javascript.jscomp, + flags = Packages.com.google.common.flags, + //Set up source input + jsSourceFile = closurefromCode(String(fileName), String(fileContents)), + sourceListArray = new java.util.ArrayList(), + externList = new java.util.ArrayList(), + options, option, FLAG_compilation_level, compiler, externExportsPath, + Compiler = Packages.com.google.javascript.jscomp.Compiler, + CommandLineRunner = Packages.com.google.javascript.jscomp.CommandLineRunner; + + logger.trace("Minifying file: " + fileName); + + baseName = (new java.io.File(fileName)).getName(); + + //Set up options + options = new jscomp.CompilerOptions(); + for (option in config.CompilerOptions) { + // options are false by default and jslint wanted an if statement in this for loop + if (config.CompilerOptions[option]) { + options[option] = config.CompilerOptions[option]; + } + + } + options.prettyPrint = keepLines || options.prettyPrint; + + FLAG_compilation_level = jscomp.CompilationLevel[config.CompilationLevel || 'SIMPLE_OPTIMIZATIONS']; + FLAG_compilation_level.setOptionsForCompilationLevel(options); + + if (config.generateSourceMaps) { + mappings = new java.util.ArrayList(); + + mappings.add(new com.google.javascript.jscomp.SourceMap.LocationMapping(fileName, baseName + ".src.js")); + options.setSourceMapLocationMappings(mappings); + options.setSourceMapOutputPath(fileName + ".map"); + } + + //If we need to pass an externs file to Closure so that it does not create aliases + //for certain symbols, do so here. + externList.addAll(CommandLineRunner.getDefaultExterns()); + if (config.externExportsPath) { + externExportsPath = config.externExportsPath; + externList.add(jscomp.SourceFile.fromFile(externExportsPath)); + } + + //Trigger the compiler + Compiler.setLoggingLevel(Packages.java.util.logging.Level[config.loggingLevel || 'WARNING']); + compiler = new Compiler(); + + //fill the sourceArrrayList; we need the ArrayList because the only overload of compile + //accepting the getDefaultExterns return value (a List) also wants the sources as a List + sourceListArray.add(jsSourceFile); + + result = compiler.compile(externList, sourceListArray, options); + if (result.success) { + optimized = String(compiler.toSource()); + + if (config.generateSourceMaps && result.sourceMap && outFileName) { + outBaseName = (new java.io.File(outFileName)).getName(); + + srcOutFileName = outFileName + ".src.js"; + outFileNameMap = outFileName + ".map"; + + //If previous .map file exists, move it to the ".src.js" + //location. Need to update the sourceMappingURL part in the + //src.js file too. + if (file.exists(outFileNameMap)) { + concatNameMap = outFileNameMap.replace(/\.map$/, '.src.js.map'); + file.saveFile(concatNameMap, file.readFile(outFileNameMap)); + file.saveFile(srcOutFileName, + fileContents.replace(/\/\# sourceMappingURL=(.+).map/, + '/# sourceMappingURL=$1.src.js.map')); + } else { + file.saveUtf8File(srcOutFileName, fileContents); + } + + writer = getFileWriter(outFileNameMap, "utf-8"); + result.sourceMap.appendTo(writer, outFileName); + writer.close(); + + //Not sure how better to do this, but right now the .map file + //leaks the full OS path in the "file" property. Manually + //modify it to not do that. + file.saveFile(outFileNameMap, + file.readFile(outFileNameMap).replace(mapRegExp, '"file":"' + baseName + '"')); + + fileContents = optimized + "\n//# sourceMappingURL=" + outBaseName + ".map"; + } else { + fileContents = optimized; + } + return fileContents; + } else { + throw new Error('Cannot closure compile file: ' + fileName + '. Skipping it.'); + } + + return fileContents; + } + }; + + return optimize; +}); +} + +if(env === 'xpconnect') { +define('xpconnect/optimize', {}); +} +/*jslint plusplus: true, nomen: true, regexp: true */ +/*global define: false */ + +define('optimize', [ 'lang', 'logger', 'env!env/optimize', 'env!env/file', 'parse', + 'pragma', 'uglifyjs', + 'source-map'], +function (lang, logger, envOptimize, file, parse, + pragma, uglify, + sourceMap) { + 'use strict'; + + var optimize, + cssImportRegExp = /\@import\s+(url\()?\s*([^);]+)\s*(\))?([\w, ]*)(;)?/ig, + cssCommentImportRegExp = /\/\*[^\*]*@import[^\*]*\*\//g, + cssUrlRegExp = /\url\(\s*([^\)]+)\s*\)?/g, + protocolRegExp = /^\w+:/, + SourceMapGenerator = sourceMap.SourceMapGenerator, + SourceMapConsumer = sourceMap.SourceMapConsumer, + es5PlusGuidance = 'If the source uses ES2015 or later syntax, please pass "optimize: \'none\'" to r.js and use an ES2015+ compatible minifier after running r.js. The included UglifyJS only understands ES5 or earlier syntax.'; + + /** + * If an URL from a CSS url value contains start/end quotes, remove them. + * This is not done in the regexp, since my regexp fu is not that strong, + * and the CSS spec allows for ' and " in the URL if they are backslash escaped. + * @param {String} url + */ + function cleanCssUrlQuotes(url) { + //Make sure we are not ending in whitespace. + //Not very confident of the css regexps above that there will not be ending + //whitespace. + url = url.replace(/\s+$/, ""); + + if (url.charAt(0) === "'" || url.charAt(0) === "\"") { + url = url.substring(1, url.length - 1); + } + + return url; + } + + function fixCssUrlPaths(fileName, path, contents, cssPrefix) { + return contents.replace(cssUrlRegExp, function (fullMatch, urlMatch) { + var firstChar, hasProtocol, parts, i, + fixedUrlMatch = cleanCssUrlQuotes(urlMatch); + + fixedUrlMatch = fixedUrlMatch.replace(lang.backSlashRegExp, "/"); + + //Only do the work for relative URLs. Skip things that start with / or #, or have + //a protocol. + firstChar = fixedUrlMatch.charAt(0); + hasProtocol = protocolRegExp.test(fixedUrlMatch); + if (firstChar !== "/" && firstChar !== "#" && !hasProtocol) { + //It is a relative URL, tack on the cssPrefix and path prefix + urlMatch = cssPrefix + path + fixedUrlMatch; + } else if (!hasProtocol) { + logger.trace(fileName + "\n URL not a relative URL, skipping: " + urlMatch); + } + + //Collapse .. and . + parts = urlMatch.split("/"); + for (i = parts.length - 1; i > 0; i--) { + if (parts[i] === ".") { + parts.splice(i, 1); + } else if (parts[i] === "..") { + if (i !== 0 && parts[i - 1] !== "..") { + parts.splice(i - 1, 2); + i -= 1; + } + } + } + + return "url(" + parts.join("/") + ")"; + }); + } + + /** + * Inlines nested stylesheets that have @import calls in them. + * @param {String} fileName the file name + * @param {String} fileContents the file contents + * @param {String} cssImportIgnore comma delimited string of files to ignore + * @param {String} cssPrefix string to be prefixed before relative URLs + * @param {Object} included an object used to track the files already imported + */ + function flattenCss(fileName, fileContents, cssImportIgnore, cssPrefix, included, topLevel) { + //Find the last slash in the name. + fileName = fileName.replace(lang.backSlashRegExp, "/"); + var endIndex = fileName.lastIndexOf("/"), + //Make a file path based on the last slash. + //If no slash, so must be just a file name. Use empty string then. + filePath = (endIndex !== -1) ? fileName.substring(0, endIndex + 1) : "", + //store a list of merged files + importList = [], + skippedList = []; + + //First make a pass by removing any commented out @import calls. + fileContents = fileContents.replace(cssCommentImportRegExp, ''); + + //Make sure we have a delimited ignore list to make matching faster + if (cssImportIgnore && cssImportIgnore.charAt(cssImportIgnore.length - 1) !== ",") { + cssImportIgnore += ","; + } + + fileContents = fileContents.replace(cssImportRegExp, function (fullMatch, urlStart, importFileName, urlEnd, mediaTypes) { + //Only process media type "all" or empty media type rules. + if (mediaTypes && ((mediaTypes.replace(/^\s\s*/, '').replace(/\s\s*$/, '')) !== "all")) { + skippedList.push(fileName); + return fullMatch; + } + + importFileName = cleanCssUrlQuotes(importFileName); + + //Ignore the file import if it is part of an ignore list. + if (cssImportIgnore && cssImportIgnore.indexOf(importFileName + ",") !== -1) { + return fullMatch; + } + + //Make sure we have a unix path for the rest of the operation. + importFileName = importFileName.replace(lang.backSlashRegExp, "/"); + + try { + //if a relative path, then tack on the filePath. + //If it is not a relative path, then the readFile below will fail, + //and we will just skip that import. + var fullImportFileName = importFileName.charAt(0) === "/" ? importFileName : filePath + importFileName, + importContents = file.readFile(fullImportFileName), + importEndIndex, importPath, flat; + + //Skip the file if it has already been included. + if (included[fullImportFileName]) { + return ''; + } + included[fullImportFileName] = true; + + //Make sure to flatten any nested imports. + flat = flattenCss(fullImportFileName, importContents, cssImportIgnore, cssPrefix, included); + importContents = flat.fileContents; + + if (flat.importList.length) { + importList.push.apply(importList, flat.importList); + } + if (flat.skippedList.length) { + skippedList.push.apply(skippedList, flat.skippedList); + } + + //Make the full import path + importEndIndex = importFileName.lastIndexOf("/"); + + //Make a file path based on the last slash. + //If no slash, so must be just a file name. Use empty string then. + importPath = (importEndIndex !== -1) ? importFileName.substring(0, importEndIndex + 1) : ""; + + //fix url() on relative import (#5) + importPath = importPath.replace(/^\.\//, ''); + + //Modify URL paths to match the path represented by this file. + importContents = fixCssUrlPaths(importFileName, importPath, importContents, cssPrefix); + + importList.push(fullImportFileName); + return importContents; + } catch (e) { + logger.warn(fileName + "\n Cannot inline css import, skipping: " + importFileName); + return fullMatch; + } + }); + + if (cssPrefix && topLevel) { + //Modify URL paths to match the path represented by this file. + fileContents = fixCssUrlPaths(fileName, '', fileContents, cssPrefix); + } + + return { + importList : importList, + skippedList: skippedList, + fileContents : fileContents + }; + } + + optimize = { + /** + * Optimizes a file that contains JavaScript content. Optionally collects + * plugin resources mentioned in a file, and then passes the content + * through an minifier if one is specified via config.optimize. + * + * @param {String} fileName the name of the file to optimize + * @param {String} fileContents the contents to optimize. If this is + * a null value, then fileName will be used to read the fileContents. + * @param {String} outFileName the name of the file to use for the + * saved optimized content. + * @param {Object} config the build config object. + * @param {Array} [pluginCollector] storage for any plugin resources + * found. + */ + jsFile: function (fileName, fileContents, outFileName, config, pluginCollector) { + if (!fileContents) { + fileContents = file.readFile(fileName); + } + + fileContents = optimize.js(fileName, fileContents, outFileName, config, pluginCollector); + + file.saveUtf8File(outFileName, fileContents); + }, + + /** + * Optimizes a file that contains JavaScript content. Optionally collects + * plugin resources mentioned in a file, and then passes the content + * through an minifier if one is specified via config.optimize. + * + * @param {String} fileName the name of the file that matches the + * fileContents. + * @param {String} fileContents the string of JS to optimize. + * @param {Object} [config] the build config object. + * @param {Array} [pluginCollector] storage for any plugin resources + * found. + */ + js: function (fileName, fileContents, outFileName, config, pluginCollector) { + var optFunc, optConfig, + parts = (String(config.optimize)).split('.'), + optimizerName = parts[0], + keepLines = parts[1] === 'keepLines', + licenseContents = ''; + + config = config || {}; + + //Apply pragmas/namespace renaming + fileContents = pragma.process(fileName, fileContents, config, 'OnSave', pluginCollector); + + //Optimize the JS files if asked. + if (optimizerName && optimizerName !== 'none') { + optFunc = envOptimize[optimizerName] || optimize.optimizers[optimizerName]; + if (!optFunc) { + throw new Error('optimizer with name of "' + + optimizerName + + '" not found for this environment'); + } + + optConfig = config[optimizerName] || {}; + if (config.generateSourceMaps) { + optConfig.generateSourceMaps = !!config.generateSourceMaps; + optConfig._buildSourceMap = config._buildSourceMap; + } + + try { + if (config.preserveLicenseComments) { + //Pull out any license comments for prepending after optimization. + try { + licenseContents = parse.getLicenseComments(fileName, fileContents); + } catch (e) { + throw new Error('Cannot parse file: ' + fileName + ' for comments. Skipping it. Error is:\n' + e.toString()); + } + } + + if (config.generateSourceMaps && licenseContents) { + optConfig.preamble = licenseContents; + licenseContents = ''; + } + + fileContents = licenseContents + optFunc(fileName, + fileContents, + outFileName, + keepLines, + optConfig); + if (optConfig._buildSourceMap && optConfig._buildSourceMap !== config._buildSourceMap) { + config._buildSourceMap = optConfig._buildSourceMap; + } + } catch (e) { + if (config.throwWhen && config.throwWhen.optimize) { + throw e; + } else { + logger.error(e); + } + } + } else { + if (config._buildSourceMap) { + config._buildSourceMap = null; + } + } + + return fileContents; + }, + + /** + * Optimizes one CSS file, inlining @import calls, stripping comments, and + * optionally removes line returns. + * @param {String} fileName the path to the CSS file to optimize + * @param {String} outFileName the path to save the optimized file. + * @param {Object} config the config object with the optimizeCss and + * cssImportIgnore options. + */ + cssFile: function (fileName, outFileName, config) { + + //Read in the file. Make sure we have a JS string. + var originalFileContents = file.readFile(fileName), + flat = flattenCss(fileName, originalFileContents, config.cssImportIgnore, config.cssPrefix, {}, true), + //Do not use the flattened CSS if there was one that was skipped. + fileContents = flat.skippedList.length ? originalFileContents : flat.fileContents, + startIndex, endIndex, buildText, comment; + + if (flat.skippedList.length) { + logger.warn('Cannot inline @imports for ' + fileName + + ',\nthe following files had media queries in them:\n' + + flat.skippedList.join('\n')); + } + + //Do comment removal. + try { + if (config.optimizeCss.indexOf(".keepComments") === -1) { + startIndex = 0; + //Get rid of comments. + while ((startIndex = fileContents.indexOf("/*", startIndex)) !== -1) { + endIndex = fileContents.indexOf("*/", startIndex + 2); + if (endIndex === -1) { + throw "Improper comment in CSS file: " + fileName; + } + comment = fileContents.substring(startIndex, endIndex); + + if (config.preserveLicenseComments && + (comment.indexOf('license') !== -1 || + comment.indexOf('opyright') !== -1 || + comment.indexOf('(c)') !== -1)) { + //Keep the comment, just increment the startIndex + startIndex = endIndex; + } else { + fileContents = fileContents.substring(0, startIndex) + fileContents.substring(endIndex + 2, fileContents.length); + startIndex = 0; + } + } + } + //Get rid of newlines. + if (config.optimizeCss.indexOf(".keepLines") === -1) { + fileContents = fileContents.replace(/[\r\n]/g, " "); + fileContents = fileContents.replace(/\s+/g, " "); + fileContents = fileContents.replace(/\{\s/g, "{"); + fileContents = fileContents.replace(/\s\}/g, "}"); + } else { + //Remove multiple empty lines. + fileContents = fileContents.replace(/(\r\n)+/g, "\r\n"); + fileContents = fileContents.replace(/(\n)+/g, "\n"); + } + //Remove unnecessary whitespace + if (config.optimizeCss.indexOf(".keepWhitespace") === -1) { + //Remove leading and trailing whitespace from lines + fileContents = fileContents.replace(/^[ \t]+/gm, ""); + fileContents = fileContents.replace(/[ \t]+$/gm, ""); + //Remove whitespace after semicolon, colon, curly brackets and commas + fileContents = fileContents.replace(/(;|:|\{|}|,)[ \t]+/g, "$1"); + //Remove whitespace before opening curly brackets + fileContents = fileContents.replace(/[ \t]+(\{)/g, "$1"); + //Truncate double whitespace + fileContents = fileContents.replace(/([ \t])+/g, "$1"); + //Remove empty lines + fileContents = fileContents.replace(/^[ \t]*[\r\n]/gm,''); + } + } catch (e) { + fileContents = originalFileContents; + logger.error("Could not optimized CSS file: " + fileName + ", error: " + e); + } + + file.saveUtf8File(outFileName, fileContents); + + //text output to stdout and/or written to build.txt file + buildText = "\n"+ outFileName.replace(config.dir, "") +"\n----------------\n"; + flat.importList.push(fileName); + buildText += flat.importList.map(function(path){ + return path.replace(config.dir, ""); + }).join("\n"); + + return { + importList: flat.importList, + buildText: buildText +"\n" + }; + }, + + /** + * Optimizes CSS files, inlining @import calls, stripping comments, and + * optionally removes line returns. + * @param {String} startDir the path to the top level directory + * @param {Object} config the config object with the optimizeCss and + * cssImportIgnore options. + */ + css: function (startDir, config) { + var buildText = "", + importList = [], + shouldRemove = config.dir && config.removeCombined, + i, fileName, result, fileList; + if (config.optimizeCss.indexOf("standard") !== -1) { + fileList = file.getFilteredFileList(startDir, /\.css$/, true); + if (fileList) { + for (i = 0; i < fileList.length; i++) { + fileName = fileList[i]; + logger.trace("Optimizing (" + config.optimizeCss + ") CSS file: " + fileName); + result = optimize.cssFile(fileName, fileName, config); + buildText += result.buildText; + if (shouldRemove) { + result.importList.pop(); + importList = importList.concat(result.importList); + } + } + } + + if (shouldRemove) { + importList.forEach(function (path) { + if (file.exists(path)) { + file.deleteFile(path); + } + }); + } + } + return buildText; + }, + + optimizers: { + uglify: function (fileName, fileContents, outFileName, keepLines, config) { + var result, existingMap, resultMap, finalMap, sourceIndex, + uconfig = {}, + existingMapPath = outFileName + '.map', + baseName = fileName && fileName.split('/').pop(); + + config = config || {}; + + lang.mixin(uconfig, config, true); + + uconfig.fromString = true; + + if (config.preamble) { + uconfig.output = {preamble: config.preamble}; + } + + + if (config.generateSourceMaps && (outFileName || config._buildSourceMap)) { + uconfig.outSourceMap = baseName + '.map'; + + if (config._buildSourceMap) { + existingMap = JSON.parse(config._buildSourceMap); + uconfig.inSourceMap = existingMap; + } else if (file.exists(existingMapPath)) { + uconfig.inSourceMap = existingMapPath; + existingMap = JSON.parse(file.readFile(existingMapPath)); + } + } + + logger.trace("Uglify file: " + fileName); + + try { + //var tempContents = fileContents.replace(/\/\/\# sourceMappingURL=.*$/, ''); + result = uglify.minify(fileContents, uconfig, baseName + '.src.js'); + if (uconfig.outSourceMap && result.map) { + resultMap = result.map; + if (!existingMap && !config._buildSourceMap) { + file.saveFile(outFileName + '.src.js', fileContents); + } + + fileContents = result.code; + + if (config._buildSourceMap) { + config._buildSourceMap = resultMap; + } else { + file.saveFile(outFileName + '.map', resultMap); + } + } else { + fileContents = result.code; + } + } catch (e) { + var errorString = e.toString(); + var isSyntaxError = /SyntaxError/.test(errorString); + throw new Error('Cannot uglify file: ' + fileName + + '. Skipping it. Error is:\n' + errorString + + (isSyntaxError ? '\n\n' + es5PlusGuidance : '')); + } + return fileContents; + } + } + }; + + return optimize; +}); +/* + * This file patches require.js to communicate with the build system. + */ + +//Using sloppy since this uses eval for some code like plugins, +//which may not be strict mode compliant. So if use strict is used +//below they will have strict rules applied and may cause an error. +/*jslint sloppy: true, nomen: true, plusplus: true, regexp: true */ +/*global require, define: true */ + +//NOT asking for require as a dependency since the goal is to modify the +//global require below +define('requirePatch', [ 'env!env/file', 'pragma', 'parse', 'lang', 'logger', 'commonJs', 'prim'], function ( + file, + pragma, + parse, + lang, + logger, + commonJs, + prim +) { + + var allowRun = true, + hasProp = lang.hasProp, + falseProp = lang.falseProp, + getOwn = lang.getOwn, + // Used to strip out use strict from toString()'d functions for the + // shim config since they will explicitly want to not be bound by strict, + // but some envs, explicitly xpcshell, adds a use strict. + useStrictRegExp = /['"]use strict['"];/g, + //Absolute path if starts with /, \, or x: + absoluteUrlRegExp = /^[\/\\]|^\w:/; + + //Turn off throwing on resolution conflict, that was just an older prim + //idea about finding errors early, but does not comply with how promises + //should operate. + prim.hideResolutionConflict = true; + + //This method should be called when the patches to require should take hold. + return function () { + if (!allowRun) { + return; + } + allowRun = false; + + var layer, + pluginBuilderRegExp = /(["']?)pluginBuilder(["']?)\s*[=\:]\s*["']([^'"\s]+)["']/, + oldNewContext = require.s.newContext, + oldDef, + + //create local undefined values for module and exports, + //so that when files are evaled in this function they do not + //see the node values used for r.js + exports, + module; + + /** + * Reset "global" build caches that are kept around between + * build layer builds. Useful to do when there are multiple + * top level requirejs.optimize() calls. + */ + require._cacheReset = function () { + //Stored raw text caches, used by browser use. + require._cachedRawText = {}; + //Stored cached file contents for reuse in other layers. + require._cachedFileContents = {}; + //Store which cached files contain a require definition. + require._cachedDefinesRequireUrls = {}; + }; + require._cacheReset(); + + /** + * Makes sure the URL is something that can be supported by the + * optimization tool. + * @param {String} url + * @returns {Boolean} + */ + require._isSupportedBuildUrl = function (url) { + //Ignore URLs with protocols, hosts or question marks, means either network + //access is needed to fetch it or it is too dynamic. Note that + //on Windows, full paths are used for some urls, which include + //the drive, like c:/something, so need to test for something other + //than just a colon. + if (url.indexOf("://") === -1 && url.indexOf("?") === -1 && + url.indexOf('empty:') !== 0 && url.indexOf('//') !== 0) { + return true; + } else { + if (!layer.ignoredUrls[url]) { + if (url.indexOf('empty:') === -1) { + logger.info('Cannot optimize network URL, skipping: ' + url); + } + layer.ignoredUrls[url] = true; + } + return false; + } + }; + + function normalizeUrlWithBase(context, moduleName, url) { + //Adjust the URL if it was not transformed to use baseUrl, but only + //if the URL is not already an absolute path. + if (require.jsExtRegExp.test(moduleName) && + !absoluteUrlRegExp.test(url)) { + url = (context.config.dir || context.config.dirBaseUrl) + url; + } + return url; + } + + //Overrides the new context call to add existing tracking features. + require.s.newContext = function (name) { + var context = oldNewContext(name), + oldEnable = context.enable, + moduleProto = context.Module.prototype, + oldInit = moduleProto.init, + oldCallPlugin = moduleProto.callPlugin; + + //Only do this for the context used for building. + if (name === '_') { + //For build contexts, do everything sync + context.nextTick = function (fn) { + fn(); + }; + + context.needFullExec = {}; + context.fullExec = {}; + context.plugins = {}; + context.buildShimExports = {}; + + //Override the shim exports function generator to just + //spit out strings that can be used in the stringified + //build output. + context.makeShimExports = function (value) { + var fn; + if (context.config.wrapShim) { + fn = function () { + var str = 'return '; + // If specifies an export that is just a global + // name, no dot for a `this.` and such, then also + // attach to the global, for `var a = {}` files + // where the function closure would hide that from + // the global object. + if (value.exports && value.exports.indexOf('.') === -1) { + str += 'root.' + value.exports + ' = '; + } + + if (value.init) { + str += '(' + value.init.toString() + .replace(useStrictRegExp, '') + '.apply(this, arguments))'; + } + if (value.init && value.exports) { + str += ' || '; + } + if (value.exports) { + str += value.exports; + } + str += ';'; + return str; + }; + } else { + fn = function () { + return '(function (global) {\n' + + ' return function () {\n' + + ' var ret, fn;\n' + + (value.init ? + (' fn = ' + value.init.toString() + .replace(useStrictRegExp, '') + ';\n' + + ' ret = fn.apply(global, arguments);\n') : '') + + (value.exports ? + ' return ret || global.' + value.exports + ';\n' : + ' return ret;\n') + + ' };\n' + + '}(this))'; + }; + } + + return fn; + }; + + context.enable = function (depMap, parent) { + var id = depMap.id, + parentId = parent && parent.map.id, + needFullExec = context.needFullExec, + fullExec = context.fullExec, + mod = getOwn(context.registry, id); + + if (mod && !mod.defined) { + if (parentId && getOwn(needFullExec, parentId)) { + needFullExec[id] = depMap; + } + + } else if ((getOwn(needFullExec, id) && falseProp(fullExec, id)) || + (parentId && getOwn(needFullExec, parentId) && + falseProp(fullExec, id))) { + context.require.undef(id); + } + + return oldEnable.apply(context, arguments); + }; + + //Override load so that the file paths can be collected. + context.load = function (moduleName, url) { + /*jslint evil: true */ + var contents, pluginBuilderMatch, builderName, + shim, shimExports; + + //Do not mark the url as fetched if it is + //not an empty: URL, used by the optimizer. + //In that case we need to be sure to call + //load() for each module that is mapped to + //empty: so that dependencies are satisfied + //correctly. + if (url.indexOf('empty:') === 0) { + delete context.urlFetched[url]; + } + + //Only handle urls that can be inlined, so that means avoiding some + //URLs like ones that require network access or may be too dynamic, + //like JSONP + if (require._isSupportedBuildUrl(url)) { + //Adjust the URL if it was not transformed to use baseUrl. + url = normalizeUrlWithBase(context, moduleName, url); + + //Save the module name to path and path to module name mappings. + layer.buildPathMap[moduleName] = url; + layer.buildFileToModule[url] = moduleName; + + if (hasProp(context.plugins, moduleName)) { + //plugins need to have their source evaled as-is. + context.needFullExec[moduleName] = true; + } + + prim().start(function () { + if (hasProp(require._cachedFileContents, url) && + (falseProp(context.needFullExec, moduleName) || + getOwn(context.fullExec, moduleName))) { + contents = require._cachedFileContents[url]; + + //If it defines require, mark it so it can be hoisted. + //Done here and in the else below, before the + //else block removes code from the contents. + //Related to #263 + if (!layer.existingRequireUrl && require._cachedDefinesRequireUrls[url]) { + layer.existingRequireUrl = url; + } + } else { + //Load the file contents, process for conditionals, then + //evaluate it. + return require._cacheReadAsync(url).then(function (text) { + contents = text; + + if (context.config.cjsTranslate && + (!context.config.shim || !lang.hasProp(context.config.shim, moduleName))) { + contents = commonJs.convert(url, contents); + } + + //If there is a read filter, run it now. + if (context.config.onBuildRead) { + contents = context.config.onBuildRead(moduleName, url, contents); + } + + contents = pragma.process(url, contents, context.config, 'OnExecute'); + + //Find out if the file contains a require() definition. Need to know + //this so we can inject plugins right after it, but before they are needed, + //and to make sure this file is first, so that define calls work. + try { + if (!layer.existingRequireUrl && parse.definesRequire(url, contents)) { + layer.existingRequireUrl = url; + require._cachedDefinesRequireUrls[url] = true; + } + } catch (e1) { + throw new Error('Parse error using esprima ' + + 'for file: ' + url + '\n' + e1); + } + }).then(function () { + if (hasProp(context.plugins, moduleName)) { + //This is a loader plugin, check to see if it has a build extension, + //otherwise the plugin will act as the plugin builder too. + pluginBuilderMatch = pluginBuilderRegExp.exec(contents); + if (pluginBuilderMatch) { + //Load the plugin builder for the plugin contents. + builderName = context.makeModuleMap(pluginBuilderMatch[3], + context.makeModuleMap(moduleName), + null, + true).id; + return require._cacheReadAsync(context.nameToUrl(builderName)); + } + } + return contents; + }).then(function (text) { + contents = text; + + //Parse out the require and define calls. + //Do this even for plugins in case they have their own + //dependencies that may be separate to how the pluginBuilder works. + try { + if (falseProp(context.needFullExec, moduleName)) { + contents = parse(moduleName, url, contents, { + insertNeedsDefine: true, + has: context.config.has, + findNestedDependencies: context.config.findNestedDependencies + }); + } + } catch (e2) { + throw new Error('Parse error using esprima ' + + 'for file: ' + url + '\n' + e2); + } + + require._cachedFileContents[url] = contents; + }); + } + }).then(function () { + if (contents) { + eval(contents); + } + + try { + //If have a string shim config, and this is + //a fully executed module, try to see if + //it created a variable in this eval scope + if (getOwn(context.needFullExec, moduleName)) { + shim = getOwn(context.config.shim, moduleName); + if (shim && shim.exports) { + shimExports = eval(shim.exports); + if (typeof shimExports !== 'undefined') { + context.buildShimExports[moduleName] = shimExports; + } + } + } + + //Need to close out completion of this module + //so that listeners will get notified that it is available. + context.completeLoad(moduleName); + } catch (e) { + //Track which module could not complete loading. + if (!e.moduleTree) { + e.moduleTree = []; + } + e.moduleTree.push(moduleName); + throw e; + } + }).then(null, function (eOuter) { + + if (!eOuter.fileName) { + eOuter.fileName = url; + } + throw eOuter; + }).end(); + } else { + //With unsupported URLs still need to call completeLoad to + //finish loading. + context.completeLoad(moduleName); + } + }; + + //Marks module has having a name, and optionally executes the + //callback, but only if it meets certain criteria. + context.execCb = function (name, cb, args, exports) { + var buildShimExports = getOwn(layer.context.buildShimExports, name); + + if (buildShimExports) { + return buildShimExports; + } else if (cb.__requireJsBuild || getOwn(layer.context.needFullExec, name)) { + return cb.apply(exports, args); + } + return undefined; + }; + + moduleProto.init = function (depMaps) { + if (context.needFullExec[this.map.id]) { + lang.each(depMaps, lang.bind(this, function (depMap) { + if (typeof depMap === 'string') { + depMap = context.makeModuleMap(depMap, + (this.map.isDefine ? this.map : this.map.parentMap), + false, true); + } + + if (!context.fullExec[depMap.id]) { + context.require.undef(depMap.id); + } + })); + } + + return oldInit.apply(this, arguments); + }; + + moduleProto.callPlugin = function () { + var map = this.map, + pluginMap = context.makeModuleMap(map.prefix), + pluginId = pluginMap.id, + pluginMod = getOwn(context.registry, pluginId); + + context.plugins[pluginId] = true; + context.needFullExec[pluginId] = map; + + //If the module is not waiting to finish being defined, + //undef it and start over, to get full execution. + if (falseProp(context.fullExec, pluginId) && (!pluginMod || pluginMod.defined)) { + context.require.undef(pluginMap.id); + } + + return oldCallPlugin.apply(this, arguments); + }; + } + + return context; + }; + + //Clear up the existing context so that the newContext modifications + //above will be active. + delete require.s.contexts._; + + /** Reset state for each build layer pass. */ + require._buildReset = function () { + var oldContext = require.s.contexts._; + + //Clear up the existing context. + delete require.s.contexts._; + + //Set up new context, so the layer object can hold onto it. + require({}); + + layer = require._layer = { + buildPathMap: {}, + buildFileToModule: {}, + buildFilePaths: [], + pathAdded: {}, + modulesWithNames: {}, + needsDefine: {}, + existingRequireUrl: "", + ignoredUrls: {}, + context: require.s.contexts._ + }; + + //Return the previous context in case it is needed, like for + //the basic config object. + return oldContext; + }; + + require._buildReset(); + + //Override define() to catch modules that just define an object, so that + //a dummy define call is not put in the build file for them. They do + //not end up getting defined via context.execCb, so we need to catch them + //at the define call. + oldDef = define; + + //This function signature does not have to be exact, just match what we + //are looking for. + define = function (name) { + if (typeof name === "string" && falseProp(layer.needsDefine, name)) { + layer.modulesWithNames[name] = true; + } + return oldDef.apply(require, arguments); + }; + + define.amd = oldDef.amd; + + //Add some utilities for plugins + require._readFile = file.readFile; + require._fileExists = function (path) { + return file.exists(path); + }; + + //Called when execManager runs for a dependency. Used to figure out + //what order of execution. + require.onResourceLoad = function (context, map) { + var id = map.id, + url; + + // Fix up any maps that need to be normalized as part of the fullExec + // plumbing for plugins to participate in the build. + if (context.plugins && lang.hasProp(context.plugins, id)) { + lang.eachProp(context.needFullExec, function(value, prop) { + // For plugin entries themselves, they do not have a map + // value in needFullExec, just a "true" entry. + if (value !== true && value.prefix === id && value.unnormalized) { + var map = context.makeModuleMap(value.originalName, value.parentMap); + context.needFullExec[map.id] = map; + } + }); + } + + //If build needed a full execution, indicate it + //has been done now. But only do it if the context is tracking + //that. Only valid for the context used in a build, not for + //other contexts being run, like for useLib, plain requirejs + //use in node/rhino. + if (context.needFullExec && getOwn(context.needFullExec, id)) { + context.fullExec[id] = map; + } + + //A plugin. + if (map.prefix) { + if (falseProp(layer.pathAdded, id)) { + layer.buildFilePaths.push(id); + //For plugins the real path is not knowable, use the name + //for both module to file and file to module mappings. + layer.buildPathMap[id] = id; + layer.buildFileToModule[id] = id; + layer.modulesWithNames[id] = true; + layer.pathAdded[id] = true; + } + } else if (map.url && require._isSupportedBuildUrl(map.url)) { + //If the url has not been added to the layer yet, and it + //is from an actual file that was loaded, add it now. + url = normalizeUrlWithBase(context, id, map.url); + if (!layer.pathAdded[url] && getOwn(layer.buildPathMap, id)) { + //Remember the list of dependencies for this layer. + layer.buildFilePaths.push(url); + layer.pathAdded[url] = true; + } + } + }; + + //Called by output of the parse() function, when a file does not + //explicitly call define, probably just require, but the parse() + //function normalizes on define() for dependency mapping and file + //ordering works correctly. + require.needsDefine = function (moduleName) { + layer.needsDefine[moduleName] = true; + }; + }; +}); +/*jslint */ +/*global define: false, console: false */ + +define('commonJs', ['env!env/file', 'parse'], function (file, parse) { + 'use strict'; + var commonJs = { + //Set to false if you do not want this file to log. Useful in environments + //like node where you want the work to happen without noise. + useLog: true, + + convertDir: function (commonJsPath, savePath) { + var fileList, i, + jsFileRegExp = /\.js$/, + fileName, convertedFileName, fileContents; + + //Get list of files to convert. + fileList = file.getFilteredFileList(commonJsPath, /\w/, true); + + //Normalize on front slashes and make sure the paths do not end in a slash. + commonJsPath = commonJsPath.replace(/\\/g, "/"); + savePath = savePath.replace(/\\/g, "/"); + if (commonJsPath.charAt(commonJsPath.length - 1) === "/") { + commonJsPath = commonJsPath.substring(0, commonJsPath.length - 1); + } + if (savePath.charAt(savePath.length - 1) === "/") { + savePath = savePath.substring(0, savePath.length - 1); + } + + //Cycle through all the JS files and convert them. + if (!fileList || !fileList.length) { + if (commonJs.useLog) { + if (commonJsPath === "convert") { + //A request just to convert one file. + console.log('\n\n' + commonJs.convert(savePath, file.readFile(savePath))); + } else { + console.log("No files to convert in directory: " + commonJsPath); + } + } + } else { + for (i = 0; i < fileList.length; i++) { + fileName = fileList[i]; + convertedFileName = fileName.replace(commonJsPath, savePath); + + //Handle JS files. + if (jsFileRegExp.test(fileName)) { + fileContents = file.readFile(fileName); + fileContents = commonJs.convert(fileName, fileContents); + file.saveUtf8File(convertedFileName, fileContents); + } else { + //Just copy the file over. + file.copyFile(fileName, convertedFileName, true); + } + } + } + }, + + /** + * Does the actual file conversion. + * + * @param {String} fileName the name of the file. + * + * @param {String} fileContents the contents of a file :) + * + * @returns {String} the converted contents + */ + convert: function (fileName, fileContents) { + //Strip out comments. + try { + var preamble = '', + commonJsProps = parse.usesCommonJs(fileName, fileContents); + + //First see if the module is not already RequireJS-formatted. + if (parse.usesAmdOrRequireJs(fileName, fileContents) || !commonJsProps) { + return fileContents; + } + + if (commonJsProps.dirname || commonJsProps.filename) { + preamble = 'var __filename = module.uri || "", ' + + '__dirname = __filename.substring(0, __filename.lastIndexOf("/") + 1); '; + } + + //Construct the wrapper boilerplate. + fileContents = 'define(function (require, exports, module) {' + + preamble + + fileContents + + '\n});\n'; + + } catch (e) { + console.log("commonJs.convert: COULD NOT CONVERT: " + fileName + ", so skipping it. Error was: " + e); + return fileContents; + } + + return fileContents; + } + }; + + return commonJs; +}); +/*jslint plusplus: true, nomen: true, regexp: true */ +/*global define, requirejs, java, process, console */ + + +define('build', function (require) { + 'use strict'; + + var build, + lang = require('lang'), + prim = require('prim'), + logger = require('logger'), + file = require('env!env/file'), + parse = require('parse'), + optimize = require('optimize'), + pragma = require('pragma'), + transform = require('transform'), + requirePatch = require('requirePatch'), + env = require('env'), + commonJs = require('commonJs'), + SourceMapGenerator = require('source-map').SourceMapGenerator, + hasProp = lang.hasProp, + getOwn = lang.getOwn, + falseProp = lang.falseProp, + endsWithSemiColonRegExp = /;\s*$/, + endsWithSlashRegExp = /[\/\\]$/, + resourceIsModuleIdRegExp = /^[\w\/\\\.]+$/, + deepCopyProps = { + layer: true + }; + + //Deep copy a config object, but do not copy over the "layer" property, + //as it can be a deeply nested structure with a full requirejs context. + function copyConfig(obj) { + return lang.deeplikeCopy(obj, deepCopyProps); + } + + prim.nextTick = function (fn) { + fn(); + }; + + //Now map require to the outermost requirejs, now that we have + //local dependencies for this module. The rest of the require use is + //manipulating the requirejs loader. + require = requirejs; + + //Caching function for performance. Attached to + //require so it can be reused in requirePatch.js. _cachedRawText + //set up by requirePatch.js + require._cacheReadAsync = function (path, encoding) { + var d; + + if (lang.hasProp(require._cachedRawText, path)) { + d = prim(); + d.resolve(require._cachedRawText[path]); + return d.promise; + } else { + return file.readFileAsync(path, encoding).then(function (text) { + require._cachedRawText[path] = text; + return text; + }); + } + }; + + function makeBuildBaseConfig() { + return { + appDir: "", + pragmas: {}, + paths: {}, + optimize: "uglify", + optimizeCss: "standard.keepLines.keepWhitespace", + inlineText: true, + isBuild: true, + optimizeAllPluginResources: false, + findNestedDependencies: false, + preserveLicenseComments: true, + writeBuildTxt: true, + //Some builds can take a while, up the default limit. + waitSeconds: 30, + //By default, all files/directories are copied, unless + //they match this regexp, by default just excludes .folders + dirExclusionRegExp: file.dirExclusionRegExp, + _buildPathToModuleIndex: {} + }; + } + + /** + * Some JS may not be valid if concatenated with other JS, in particular + * the style of omitting semicolons and rely on ASI. Add a semicolon in + * those cases. + */ + function addSemiColon(text, config) { + if (config.skipSemiColonInsertion || endsWithSemiColonRegExp.test(text)) { + return text; + } else { + return text + ";"; + } + } + + function endsWithSlash(dirName) { + if (dirName.charAt(dirName.length - 1) !== "/") { + dirName += "/"; + } + return dirName; + } + + function endsWithNewLine(text) { + if (text.charAt(text.length - 1) !== "\n") { + text += "\n"; + } + return text; + } + + //Method used by plugin writeFile calls, defined up here to avoid + //jslint warning about "making a function in a loop". + function makeWriteFile(namespace, layer) { + function writeFile(name, contents) { + logger.trace('Saving plugin-optimized file: ' + name); + file.saveUtf8File(name, contents); + } + + writeFile.asModule = function (moduleName, fileName, contents) { + writeFile(fileName, + build.toTransport(namespace, moduleName, fileName, contents, layer)); + }; + + return writeFile; + } + + /** + * Appends singleContents to fileContents and returns the result. If a sourceMapGenerator + * is provided, adds singleContents to the source map. + * + * @param {string} fileContents - The file contents to which to append singleContents + * @param {string} singleContents - The additional contents to append to fileContents + * @param {string} path - An absolute path of a file whose name to use in the source map. + * The file need not actually exist if the code in singleContents is generated. + * @param {{out: ?string, baseUrl: ?string}} config - The build configuration object. + * @param {?{_buildPath: ?string}} module - An object with module information. + * @param {?SourceMapGenerator} sourceMapGenerator - An instance of Mozilla's SourceMapGenerator, + * or null if no source map is being generated. + * @returns {string} fileContents with singleContents appended + */ + function appendToFileContents(fileContents, singleContents, path, config, module, sourceMapGenerator) { + var refPath, sourceMapPath, resourcePath, pluginId, sourceMapLineNumber, lineCount, parts, i; + if (sourceMapGenerator) { + if (config.out) { + refPath = config.baseUrl; + } else if (module && module._buildPath) { + refPath = module._buildPath; + } else { + refPath = ""; + } + parts = path.split('!'); + if (parts.length === 1) { + //Not a plugin resource, fix the path + sourceMapPath = build.makeRelativeFilePath(refPath, path); + } else { + //Plugin resource. If it looks like just a plugin + //followed by a module ID, pull off the plugin + //and put it at the end of the name, otherwise + //just leave it alone. + pluginId = parts.shift(); + resourcePath = parts.join('!'); + if (resourceIsModuleIdRegExp.test(resourcePath)) { + sourceMapPath = build.makeRelativeFilePath(refPath, require.toUrl(resourcePath)) + + '!' + pluginId; + } else { + sourceMapPath = path; + } + } + + sourceMapLineNumber = fileContents.split('\n').length - 1; + lineCount = singleContents.split('\n').length; + for (i = 1; i <= lineCount; i += 1) { + sourceMapGenerator.addMapping({ + generated: { + line: sourceMapLineNumber + i, + column: 0 + }, + original: { + line: i, + column: 0 + }, + source: sourceMapPath + }); + } + + //Store the content of the original in the source + //map since other transforms later like minification + //can mess up translating back to the original + //source. + sourceMapGenerator.setSourceContent(sourceMapPath, singleContents); + } + fileContents += singleContents; + return fileContents; + } + + /** + * Main API entry point into the build. The args argument can either be + * an array of arguments (like the onese passed on a command-line), + * or it can be a JavaScript object that has the format of a build profile + * file. + * + * If it is an object, then in addition to the normal properties allowed in + * a build profile file, the object should contain one other property: + * + * The object could also contain a "buildFile" property, which is a string + * that is the file path to a build profile that contains the rest + * of the build profile directives. + * + * This function does not return a status, it should throw an error if + * there is a problem completing the build. + */ + build = function (args) { + var buildFile, cmdConfig, errorMsg, errorStack, stackMatch, errorTree, + i, j, errorMod, + stackRegExp = /( {4}at[^\n]+)\n/, + standardIndent = ' '; + + return prim().start(function () { + if (!args || lang.isArray(args)) { + if (!args || args.length < 1) { + logger.error("build.js buildProfile.js\n" + + "where buildProfile.js is the name of the build file (see example.build.js for hints on how to make a build file)."); + return undefined; + } + + //Next args can include a build file path as well as other build args. + //build file path comes first. If it does not contain an = then it is + //a build file path. Otherwise, just all build args. + if (args[0].indexOf("=") === -1) { + buildFile = args[0]; + args.splice(0, 1); + } + + //Remaining args are options to the build + cmdConfig = build.convertArrayToObject(args); + cmdConfig.buildFile = buildFile; + } else { + cmdConfig = args; + } + + return build._run(cmdConfig); + }).then(null, function (e) { + var err; + + errorMsg = e.toString(); + errorTree = e.moduleTree; + stackMatch = stackRegExp.exec(errorMsg); + + if (stackMatch) { + errorMsg += errorMsg.substring(0, stackMatch.index + stackMatch[0].length + 1); + } + + //If a module tree that shows what module triggered the error, + //print it out. + if (errorTree && errorTree.length > 0) { + errorMsg += '\nIn module tree:\n'; + + for (i = errorTree.length - 1; i > -1; i--) { + errorMod = errorTree[i]; + if (errorMod) { + for (j = errorTree.length - i; j > -1; j--) { + errorMsg += standardIndent; + } + errorMsg += errorMod + '\n'; + } + } + + logger.error(errorMsg); + } + + errorStack = e.stack; + + if (typeof args === 'string' && args.indexOf('stacktrace=true') !== -1) { + errorMsg += '\n' + errorStack; + } else { + if (!stackMatch && errorStack) { + //Just trim out the first "at" in the stack. + stackMatch = stackRegExp.exec(errorStack); + if (stackMatch) { + errorMsg += '\n' + stackMatch[0] || ''; + } + } + } + + err = new Error(errorMsg); + err.originalError = e; + throw err; + }); + }; + + build._run = function (cmdConfig) { + var buildPaths, fileName, fileNames, + paths, i, + baseConfig, config, + modules, srcPath, buildContext, + destPath, moduleMap, parentModuleMap, context, + resources, resource, plugin, fileContents, + pluginProcessed = {}, + buildFileContents = "", + pluginCollector = {}; + + return prim().start(function () { + var prop; + + //Can now run the patches to require.js to allow it to be used for + //build generation. Do it here instead of at the top of the module + //because we want normal require behavior to load the build tool + //then want to switch to build mode. + requirePatch(); + + config = build.createConfig(cmdConfig); + paths = config.paths; + + //Remove the previous build dir, in case it contains source transforms, + //like the ones done with onBuildRead and onBuildWrite. + if (config.dir && !config.keepBuildDir && file.exists(config.dir)) { + file.deleteFile(config.dir); + } + + if (!config.out && !config.cssIn) { + //This is not just a one-off file build but a full build profile, with + //lots of files to process. + + //First copy all the baseUrl content + file.copyDir((config.appDir || config.baseUrl), config.dir, /\w/, true); + + //Adjust baseUrl if config.appDir is in play, and set up build output paths. + buildPaths = {}; + if (config.appDir) { + //All the paths should be inside the appDir, so just adjust + //the paths to use the dirBaseUrl + for (prop in paths) { + if (hasProp(paths, prop)) { + buildPaths[prop] = paths[prop].replace(config.appDir, config.dir); + } + } + } else { + //If no appDir, then make sure to copy the other paths to this directory. + for (prop in paths) { + if (hasProp(paths, prop)) { + //Set up build path for each path prefix, but only do so + //if the path falls out of the current baseUrl + if (paths[prop].indexOf(config.baseUrl) === 0) { + buildPaths[prop] = paths[prop].replace(config.baseUrl, config.dirBaseUrl); + } else { + buildPaths[prop] = paths[prop] === 'empty:' ? 'empty:' : prop; + + //Make sure source path is fully formed with baseUrl, + //if it is a relative URL. + srcPath = paths[prop]; + if (srcPath.indexOf('/') !== 0 && srcPath.indexOf(':') === -1) { + srcPath = config.baseUrl + srcPath; + } + + destPath = config.dirBaseUrl + buildPaths[prop]; + + //Skip empty: paths + if (srcPath !== 'empty:') { + //If the srcPath is a directory, copy the whole directory. + if (file.exists(srcPath) && file.isDirectory(srcPath)) { + //Copy files to build area. Copy all files (the /\w/ regexp) + file.copyDir(srcPath, destPath, /\w/, true); + } else { + //Try a .js extension + srcPath += '.js'; + destPath += '.js'; + file.copyFile(srcPath, destPath); + } + } + } + } + } + } + } + + //Figure out source file location for each module layer. Do this by seeding require + //with source area configuration. This is needed so that later the module layers + //can be manually copied over to the source area, since the build may be + //require multiple times and the above copyDir call only copies newer files. + require({ + baseUrl: config.baseUrl, + paths: paths, + packagePaths: config.packagePaths, + packages: config.packages + }); + buildContext = require.s.contexts._; + modules = config.modules; + + if (modules) { + modules.forEach(function (module) { + if (module.name) { + module._sourcePath = buildContext.nameToUrl(module.name); + //If the module does not exist, and this is not a "new" module layer, + //as indicated by a true "create" property on the module, and + //it is not a plugin-loaded resource, and there is no + //'rawText' containing the module's source then throw an error. + if (!file.exists(module._sourcePath) && !module.create && + module.name.indexOf('!') === -1 && + (!config.rawText || !lang.hasProp(config.rawText, module.name))) { + throw new Error("ERROR: module path does not exist: " + + module._sourcePath + " for module named: " + module.name + + ". Path is relative to: " + file.absPath('.')); + } + } + }); + } + + if (config.out) { + //Just set up the _buildPath for the module layer. + require(config); + if (!config.cssIn) { + config.modules[0]._buildPath = typeof config.out === 'function' ? + 'FUNCTION' : config.out; + } + } else if (!config.cssIn) { + //Now set up the config for require to use the build area, and calculate the + //build file locations. Pass along any config info too. + baseConfig = { + baseUrl: config.dirBaseUrl, + paths: buildPaths + }; + + lang.mixin(baseConfig, config); + require(baseConfig); + + if (modules) { + modules.forEach(function (module) { + if (module.name) { + module._buildPath = buildContext.nameToUrl(module.name, null); + + //If buildPath and sourcePath are the same, throw since this + //would result in modifying source. This condition can happen + //with some more tricky paths: config and appDir/baseUrl + //setting, which is a sign of incorrect config. + if (module._buildPath === module._sourcePath && + !config.allowSourceOverwrites) { + throw new Error('Module ID \'' + module.name + + '\' has a source path that is same as output path: ' + + module._sourcePath + + '. Stopping, config is malformed.'); + } + + // Copy the file, but only if it is not provided in rawText. + if (!module.create && (!config.rawText || !lang.hasProp(config.rawText, module.name))) { + file.copyFile(module._sourcePath, module._buildPath); + } + } + }); + } + } + + //Run CSS optimizations before doing JS module tracing, to allow + //things like text loader plugins loading CSS to get the optimized + //CSS. + if (config.optimizeCss && config.optimizeCss !== "none" && config.dir) { + buildFileContents += optimize.css(config.dir, config); + } + }).then(function() { + baseConfig = copyConfig(require.s.contexts._.config); + }).then(function () { + var actions = []; + + if (modules) { + actions = modules.map(function (module, i) { + return function () { + //Save off buildPath to module index in a hash for quicker + //lookup later. + config._buildPathToModuleIndex[file.normalize(module._buildPath)] = i; + + //Call require to calculate dependencies. + return build.traceDependencies(module, config, baseConfig) + .then(function (layer) { + module.layer = layer; + }); + }; + }); + + return prim.serial(actions); + } + }).then(function () { + var actions; + + if (modules) { + //Now build up shadow layers for anything that should be excluded. + //Do this after tracing dependencies for each module, in case one + //of those modules end up being one of the excluded values. + actions = modules.map(function (module) { + return function () { + if (module.exclude) { + module.excludeLayers = []; + return prim.serial(module.exclude.map(function (exclude, i) { + return function () { + //See if it is already in the list of modules. + //If not trace dependencies for it. + var found = build.findBuildModule(exclude, modules); + if (found) { + module.excludeLayers[i] = found; + } else { + return build.traceDependencies({name: exclude}, config, baseConfig) + .then(function (layer) { + module.excludeLayers[i] = { layer: layer }; + }); + } + }; + })); + } + }; + }); + + return prim.serial(actions); + } + }).then(function () { + if (modules) { + return prim.serial(modules.map(function (module) { + return function () { + if (module.exclude) { + //module.exclude is an array of module names. For each one, + //get the nested dependencies for it via a matching entry + //in the module.excludeLayers array. + module.exclude.forEach(function (excludeModule, i) { + var excludeLayer = module.excludeLayers[i].layer, + map = excludeLayer.buildFileToModule; + excludeLayer.buildFilePaths.forEach(function(filePath){ + build.removeModulePath(map[filePath], filePath, module.layer); + }); + }); + } + if (module.excludeShallow) { + //module.excludeShallow is an array of module names. + //shallow exclusions are just that module itself, and not + //its nested dependencies. + module.excludeShallow.forEach(function (excludeShallowModule) { + var path = getOwn(module.layer.buildPathMap, excludeShallowModule); + if (path) { + build.removeModulePath(excludeShallowModule, path, module.layer); + } + }); + } + + //Flatten them and collect the build output for each module. + return build.flattenModule(module, module.layer, config).then(function (builtModule) { + var finalText, baseName; + //Save it to a temp file for now, in case there are other layers that + //contain optimized content that should not be included in later + //layer optimizations. See issue #56. + if (module._buildPath === 'FUNCTION') { + module._buildText = builtModule.text; + module._buildSourceMap = builtModule.sourceMap; + } else { + finalText = builtModule.text; + if (builtModule.sourceMap) { + baseName = module._buildPath.split('/'); + baseName = baseName.pop(); + finalText += '\n//# sourceMappingURL=' + baseName + '.map'; + file.saveUtf8File(module._buildPath + '.map', builtModule.sourceMap); + } + file.saveUtf8File(module._buildPath + '-temp', finalText); + + } + buildFileContents += builtModule.buildText; + }); + }; + })); + } + }).then(function () { + var moduleName, outOrigSourceMap, + bundlesConfig = {}, + bundlesConfigOutFile = config.bundlesConfigOutFile; + + if (modules) { + //Now move the build layers to their final position. + modules.forEach(function (module) { + var entryConfig, + finalPath = module._buildPath; + + if (finalPath !== 'FUNCTION') { + if (file.exists(finalPath)) { + file.deleteFile(finalPath); + } + file.renameFile(finalPath + '-temp', finalPath); + + //If bundles config should be written out, scan the + //built file for module IDs. Favor doing this reparse + //since tracking the IDs as the file is built has some + //edge cases around files that had more than one ID in + //them already, and likely loader plugin-written contents. + if (bundlesConfigOutFile) { + entryConfig = bundlesConfig[module.name] = []; + var bundleContents = file.readFile(finalPath); + var excludeMap = {}; + excludeMap[module.name] = true; + var parsedIds = parse.getAllNamedDefines(bundleContents, excludeMap); + entryConfig.push.apply(entryConfig, parsedIds); + } + + //And finally, if removeCombined is specified, remove + //any of the files that were used in this layer. + //Be sure not to remove other build layers. + if (config.removeCombined && !config.out) { + module.layer.buildFilePaths.forEach(function (path) { + var isLayer = modules.some(function (mod) { + return mod._buildPath === path; + }), + relPath = build.makeRelativeFilePath(config.dir, path); + + if (file.exists(path) && + // not a build layer target + !isLayer && + // not outside the build directory + relPath.indexOf('..') !== 0) { + file.deleteFile(path); + } + }); + } + } + + //Signal layer is done + if (config.onModuleBundleComplete) { + config.onModuleBundleComplete(module.onCompleteData); + } + }); + + //Write out bundles config, if it is wanted. + if (bundlesConfigOutFile) { + var text = file.readFile(bundlesConfigOutFile); + text = transform.modifyConfig(text, function (config) { + if (!config.bundles) { + config.bundles = {}; + } + + lang.eachProp(bundlesConfig, function (value, prop) { + config.bundles[prop] = value; + }); + + return config; + }); + + file.saveUtf8File(bundlesConfigOutFile, text); + } + } + + //If removeCombined in play, remove any empty directories that + //may now exist because of its use + if (config.removeCombined && !config.out && config.dir) { + file.deleteEmptyDirs(config.dir); + } + + //Do other optimizations. + if (config.out && !config.cssIn) { + //Just need to worry about one JS file. + fileName = config.modules[0]._buildPath; + if (fileName === 'FUNCTION') { + outOrigSourceMap = config.modules[0]._buildSourceMap; + config._buildSourceMap = outOrigSourceMap; + config.modules[0]._buildText = optimize.js((config.modules[0].name || + config.modules[0].include[0] || + fileName) + '.build.js', + config.modules[0]._buildText, + null, + config); + if (config._buildSourceMap && config._buildSourceMap !== outOrigSourceMap) { + config.modules[0]._buildSourceMap = config._buildSourceMap; + config._buildSourceMap = null; + } + } else { + optimize.jsFile(fileName, null, fileName, config); + } + } else if (!config.cssIn) { + //Normal optimizations across modules. + + //JS optimizations. + fileNames = file.getFilteredFileList(config.dir, /\.js$/, true); + fileNames.forEach(function (fileName) { + var cfg, override, moduleIndex; + + //Generate the module name from the config.dir root. + moduleName = fileName.replace(config.dir, ''); + //Get rid of the extension + moduleName = moduleName.substring(0, moduleName.length - 3); + + //If there is an override for a specific layer build module, + //and this file is that module, mix in the override for use + //by optimize.jsFile. + moduleIndex = getOwn(config._buildPathToModuleIndex, fileName); + //Normalize, since getOwn could have returned undefined + moduleIndex = moduleIndex === 0 || moduleIndex > 0 ? moduleIndex : -1; + + //Try to avoid extra work if the other files do not need to + //be read. Build layers should be processed at the very + //least for optimization. + if (moduleIndex > -1 || !config.skipDirOptimize || + config.normalizeDirDefines === "all" || + config.cjsTranslate) { + //Convert the file to transport format, but without a name + //inserted (by passing null for moduleName) since the files are + //standalone, one module per file. + fileContents = file.readFile(fileName); + + + //For builds, if wanting cjs translation, do it now, so that + //the individual modules can be loaded cross domain via + //plain script tags. + if (config.cjsTranslate && + (!config.shim || !lang.hasProp(config.shim, moduleName))) { + fileContents = commonJs.convert(fileName, fileContents); + } + + if (moduleIndex === -1) { + if (config.onBuildRead) { + fileContents = config.onBuildRead(moduleName, + fileName, + fileContents); + } + + //Only do transport normalization if this is not a build + //layer (since it was already normalized) and if + //normalizeDirDefines indicated all should be done. + if (config.normalizeDirDefines === "all") { + fileContents = build.toTransport(config.namespace, + null, + fileName, + fileContents); + } + + if (config.onBuildWrite) { + fileContents = config.onBuildWrite(moduleName, + fileName, + fileContents); + } + } + + override = moduleIndex > -1 ? + config.modules[moduleIndex].override : null; + if (override) { + cfg = build.createOverrideConfig(config, override); + } else { + cfg = config; + } + + if (moduleIndex > -1 || !config.skipDirOptimize) { + optimize.jsFile(fileName, fileContents, fileName, cfg, pluginCollector); + } + } + }); + + //Normalize all the plugin resources. + context = require.s.contexts._; + + for (moduleName in pluginCollector) { + if (hasProp(pluginCollector, moduleName)) { + parentModuleMap = context.makeModuleMap(moduleName); + resources = pluginCollector[moduleName]; + for (i = 0; i < resources.length; i++) { + resource = resources[i]; + moduleMap = context.makeModuleMap(resource, parentModuleMap); + if (falseProp(context.plugins, moduleMap.prefix)) { + //Set the value in context.plugins so it + //will be evaluated as a full plugin. + context.plugins[moduleMap.prefix] = true; + + //Do not bother if the plugin is not available. + if (!file.exists(require.toUrl(moduleMap.prefix + '.js'))) { + continue; + } + + //Rely on the require in the build environment + //to be synchronous + context.require([moduleMap.prefix]); + + //Now that the plugin is loaded, redo the moduleMap + //since the plugin will need to normalize part of the path. + moduleMap = context.makeModuleMap(resource, parentModuleMap); + } + + //Only bother with plugin resources that can be handled + //processed by the plugin, via support of the writeFile + //method. + if (falseProp(pluginProcessed, moduleMap.id)) { + //Only do the work if the plugin was really loaded. + //Using an internal access because the file may + //not really be loaded. + plugin = getOwn(context.defined, moduleMap.prefix); + if (plugin && plugin.writeFile) { + plugin.writeFile( + moduleMap.prefix, + moduleMap.name, + require, + makeWriteFile( + config.namespace + ), + context.config + ); + } + + pluginProcessed[moduleMap.id] = true; + } + } + + } + } + + //console.log('PLUGIN COLLECTOR: ' + JSON.stringify(pluginCollector, null, " ")); + + + //All module layers are done, write out the build.txt file. + if (config.writeBuildTxt) { + file.saveUtf8File(config.dir + "build.txt", buildFileContents); + } + } + + //If just have one CSS file to optimize, do that here. + if (config.cssIn) { + buildFileContents += optimize.cssFile(config.cssIn, config.out, config).buildText; + } + + if (typeof config.out === 'function') { + config.out(config.modules[0]._buildText, config.modules[0]._buildSourceMap); + } + + //Print out what was built into which layers. + if (buildFileContents) { + logger.info(buildFileContents); + return buildFileContents; + } + + return ''; + }); + }; + + /** + * Converts command line args like "paths.foo=../some/path" + * result.paths = { foo: '../some/path' } where prop = paths, + * name = paths.foo and value = ../some/path, so it assumes the + * name=value splitting has already happened. + */ + function stringDotToObj(result, name, value) { + var parts = name.split('.'); + + parts.forEach(function (prop, i) { + if (i === parts.length - 1) { + result[prop] = value; + } else { + if (falseProp(result, prop)) { + result[prop] = {}; + } + result = result[prop]; + } + + }); + } + + build.objProps = { + paths: true, + wrap: true, + pragmas: true, + pragmasOnSave: true, + has: true, + hasOnSave: true, + uglify: true, + uglify2: true, + closure: true, + map: true, + throwWhen: true + }; + + build.hasDotPropMatch = function (prop) { + var dotProp, + index = prop.indexOf('.'); + + if (index !== -1) { + dotProp = prop.substring(0, index); + return hasProp(build.objProps, dotProp); + } + return false; + }; + + /** + * Converts an array that has String members of "name=value" + * into an object, where the properties on the object are the names in the array. + * Also converts the strings "true" and "false" to booleans for the values. + * member name/value pairs, and converts some comma-separated lists into + * arrays. + * @param {Array} ary + */ + build.convertArrayToObject = function (ary) { + var result = {}, i, separatorIndex, prop, value, + needArray = { + "include": true, + "exclude": true, + "excludeShallow": true, + "insertRequire": true, + "stubModules": true, + "deps": true, + "mainConfigFile": true, + "wrap.startFile": true, + "wrap.endFile": true + }; + + for (i = 0; i < ary.length; i++) { + separatorIndex = ary[i].indexOf("="); + if (separatorIndex === -1) { + throw "Malformed name/value pair: [" + ary[i] + "]. Format should be name=value"; + } + + value = ary[i].substring(separatorIndex + 1, ary[i].length); + if (value === "true") { + value = true; + } else if (value === "false") { + value = false; + } + + prop = ary[i].substring(0, separatorIndex); + + //Convert to array if necessary + if (getOwn(needArray, prop)) { + value = value.split(","); + } + + if (build.hasDotPropMatch(prop)) { + stringDotToObj(result, prop, value); + } else { + result[prop] = value; + } + } + return result; //Object + }; + + build.makeAbsPath = function (path, absFilePath) { + if (!absFilePath) { + return path; + } + + //Add abspath if necessary. If path starts with a slash or has a colon, + //then already is an abolute path. + if (path.indexOf('/') !== 0 && path.indexOf(':') === -1) { + path = absFilePath + + (absFilePath.charAt(absFilePath.length - 1) === '/' ? '' : '/') + + path; + path = file.normalize(path); + } + return path.replace(lang.backSlashRegExp, '/'); + }; + + build.makeAbsObject = function (props, obj, absFilePath) { + var i, prop; + if (obj) { + for (i = 0; i < props.length; i++) { + prop = props[i]; + if (hasProp(obj, prop) && typeof obj[prop] === 'string') { + obj[prop] = build.makeAbsPath(obj[prop], absFilePath); + } + } + } + }; + + /** + * For any path in a possible config, make it absolute relative + * to the absFilePath passed in. + */ + build.makeAbsConfig = function (config, absFilePath) { + var props, prop, i; + + props = ["appDir", "dir", "baseUrl"]; + for (i = 0; i < props.length; i++) { + prop = props[i]; + + if (getOwn(config, prop)) { + //Add abspath if necessary, make sure these paths end in + //slashes + if (prop === "baseUrl") { + config.originalBaseUrl = config.baseUrl; + if (config.appDir) { + //If baseUrl with an appDir, the baseUrl is relative to + //the appDir, *not* the absFilePath. appDir and dir are + //made absolute before baseUrl, so this will work. + config.baseUrl = build.makeAbsPath(config.originalBaseUrl, config.appDir); + } else { + //The dir output baseUrl is same as regular baseUrl, both + //relative to the absFilePath. + config.baseUrl = build.makeAbsPath(config[prop], absFilePath); + } + } else { + config[prop] = build.makeAbsPath(config[prop], absFilePath); + } + + config[prop] = endsWithSlash(config[prop]); + } + } + + build.makeAbsObject((config.out === "stdout" ? ["cssIn"] : ["out", "cssIn"]), + config, absFilePath); + build.makeAbsObject(["startFile", "endFile"], config.wrap, absFilePath); + build.makeAbsObject(["externExportsPath"], config.closure, absFilePath); + }; + + /** + * Creates a relative path to targetPath from refPath. + * Only deals with file paths, not folders. If folders, + * make sure paths end in a trailing '/'. + */ + build.makeRelativeFilePath = function (refPath, targetPath) { + var i, dotLength, finalParts, length, targetParts, targetName, + refParts = refPath.split('/'), + hasEndSlash = endsWithSlashRegExp.test(targetPath), + dotParts = []; + + targetPath = file.normalize(targetPath); + if (hasEndSlash && !endsWithSlashRegExp.test(targetPath)) { + targetPath += '/'; + } + targetParts = targetPath.split('/'); + //Pull off file name + targetName = targetParts.pop(); + + //Also pop off the ref file name to make the matches against + //targetParts equivalent. + refParts.pop(); + + length = refParts.length; + + for (i = 0; i < length; i += 1) { + if (refParts[i] !== targetParts[i]) { + break; + } + } + + //Now i is the index in which they diverge. + finalParts = targetParts.slice(i); + + dotLength = length - i; + for (i = 0; i > -1 && i < dotLength; i += 1) { + dotParts.push('..'); + } + + return dotParts.join('/') + (dotParts.length ? '/' : '') + + finalParts.join('/') + (finalParts.length ? '/' : '') + + targetName; + }; + + build.nestedMix = { + paths: true, + has: true, + hasOnSave: true, + pragmas: true, + pragmasOnSave: true + }; + + /** + * Mixes additional source config into target config, and merges some + * nested config, like paths, correctly. + */ + function mixConfig(target, source, skipArrays) { + var prop, value, isArray, targetValue; + + for (prop in source) { + if (hasProp(source, prop)) { + //If the value of the property is a plain object, then + //allow a one-level-deep mixing of it. + value = source[prop]; + isArray = lang.isArray(value); + if (typeof value === 'object' && value && + !isArray && !lang.isFunction(value) && + !lang.isRegExp(value)) { + + // TODO: need to generalize this work, maybe also reuse + // the work done in requirejs configure, perhaps move to + // just a deep copy/merge overall. However, given the + // amount of observable change, wait for a dot release. + // This change is in relation to #645 + if (prop === 'map') { + if (!target.map) { + target.map = {}; + } + lang.deepMix(target.map, source.map); + } else { + target[prop] = lang.mixin({}, target[prop], value, true); + } + } else if (isArray) { + if (!skipArrays) { + // Some config, like packages, are arrays. For those, + // just merge the results. + targetValue = target[prop]; + if (lang.isArray(targetValue)) { + target[prop] = targetValue.concat(value); + } else { + target[prop] = value; + } + } + } else { + target[prop] = value; + } + } + } + + //Set up log level since it can affect if errors are thrown + //or caught and passed to errbacks while doing config setup. + if (lang.hasProp(target, 'logLevel')) { + logger.logLevel(target.logLevel); + } + } + + /** + * Converts a wrap.startFile or endFile to be start/end as a string. + * the startFile/endFile values can be arrays. + */ + function flattenWrapFile(config, keyName, absFilePath) { + var wrap = config.wrap, + keyFileName = keyName + 'File', + keyMapName = '__' + keyName + 'Map'; + + if (typeof wrap[keyName] !== 'string' && wrap[keyFileName]) { + wrap[keyName] = ''; + if (typeof wrap[keyFileName] === 'string') { + wrap[keyFileName] = [wrap[keyFileName]]; + } + wrap[keyMapName] = []; + wrap[keyFileName].forEach(function (fileName) { + var absPath = build.makeAbsPath(fileName, absFilePath), + fileText = endsWithNewLine(file.readFile(absPath)); + wrap[keyMapName].push(function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, fileText, absPath, cfg, null, sourceMapGenerator); + }); + wrap[keyName] += fileText; + }); + } else if (wrap[keyName] === null || wrap[keyName] === undefined) { + //Allow missing one, just set to empty string. + wrap[keyName] = ''; + } else if (typeof wrap[keyName] === 'string') { + wrap[keyName] = endsWithNewLine(wrap[keyName]); + wrap[keyMapName] = [ + function (fileContents, cfg, sourceMapGenerator) { + var absPath = build.makeAbsPath("config-wrap-" + keyName + "-default.js", absFilePath); + return appendToFileContents(fileContents, wrap[keyName], absPath, cfg, null, sourceMapGenerator); + } + ]; + } else { + throw new Error('wrap.' + keyName + ' or wrap.' + keyFileName + ' malformed'); + } + } + + function normalizeWrapConfig(config, absFilePath) { + //Get any wrap text. + try { + if (config.wrap) { + if (config.wrap === true) { + //Use default values. + config.wrap = { + start: '(function () {\n', + end: '}());', + __startMap: [ + function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, "(function () {\n", + build.makeAbsPath("config-wrap-start-default.js", + absFilePath), cfg, null, + sourceMapGenerator); + } + ], + __endMap: [ + function (fileContents, cfg, sourceMapGenerator) { + return appendToFileContents(fileContents, "}());", + build.makeAbsPath("config-wrap-end-default.js", absFilePath), + cfg, null, sourceMapGenerator); + } + ] + }; + } else { + flattenWrapFile(config, 'start', absFilePath); + flattenWrapFile(config, 'end', absFilePath); + } + } + } catch (wrapError) { + throw new Error('Malformed wrap config: ' + wrapError.toString()); + } + } + + /** + * Creates a config object for an optimization build. + * It will also read the build profile if it is available, to create + * the configuration. + * + * @param {Object} cfg config options that take priority + * over defaults and ones in the build file. These options could + * be from a command line, for instance. + * + * @param {Object} the created config object. + */ + build.createConfig = function (cfg) { + /*jslint evil: true */ + var buildFileContents, buildFileConfig, mainConfig, + mainConfigFile, mainConfigPath, buildFile, absFilePath, + config = {}, + buildBaseConfig = makeBuildBaseConfig(); + + //Make sure all paths are relative to current directory. + absFilePath = file.absPath('.'); + build.makeAbsConfig(cfg, absFilePath); + build.makeAbsConfig(buildBaseConfig, absFilePath); + + lang.mixin(config, buildBaseConfig); + lang.mixin(config, cfg, true); + + //Set up log level early since it can affect if errors are thrown + //or caught and passed to errbacks, even while constructing config. + if (lang.hasProp(config, 'logLevel')) { + logger.logLevel(config.logLevel); + } + + if (config.buildFile) { + //A build file exists, load it to get more config. + buildFile = file.absPath(config.buildFile); + + //Find the build file, and make sure it exists, if this is a build + //that has a build profile, and not just command line args with an in=path + if (!file.exists(buildFile)) { + throw new Error("ERROR: build file does not exist: " + buildFile); + } + + absFilePath = config.baseUrl = file.absPath(file.parent(buildFile)); + + //Load build file options. + buildFileContents = file.readFile(buildFile); + try { + //Be a bit lenient in the file ending in a ; or ending with + //a //# sourceMappingUrl comment, mostly for compiled languages + //that create a config, like typescript. + buildFileContents = buildFileContents + .replace(/\/\/\#[^\n\r]+[\n\r]*$/, '') + .trim() + .replace(/;$/, ''); + + buildFileConfig = eval("(" + buildFileContents + ")"); + build.makeAbsConfig(buildFileConfig, absFilePath); + + //Mix in the config now so that items in mainConfigFile can + //be resolved relative to them if necessary, like if appDir + //is set here, but the baseUrl is in mainConfigFile. Will + //re-mix in the same build config later after mainConfigFile + //is processed, since build config should take priority. + mixConfig(config, buildFileConfig); + } catch (e) { + throw new Error("Build file " + buildFile + " is malformed: " + e); + } + } + + mainConfigFile = config.mainConfigFile || (buildFileConfig && buildFileConfig.mainConfigFile); + if (mainConfigFile) { + if (typeof mainConfigFile === 'string') { + mainConfigFile = [mainConfigFile]; + } + + mainConfigFile.forEach(function (configFile) { + configFile = build.makeAbsPath(configFile, absFilePath); + if (!file.exists(configFile)) { + throw new Error(configFile + ' does not exist.'); + } + try { + mainConfig = parse.findConfig(file.readFile(configFile)).config; + } catch (configError) { + throw new Error('The config in mainConfigFile ' + + configFile + + ' cannot be used because it cannot be evaluated' + + ' correctly while running in the optimizer. Try only' + + ' using a config that is also valid JSON, or do not use' + + ' mainConfigFile and instead copy the config values needed' + + ' into a build file or command line arguments given to the optimizer.\n' + + 'Source error from parsing: ' + configFile + ': ' + configError); + } + if (mainConfig) { + mainConfigPath = configFile.substring(0, configFile.lastIndexOf('/')); + + //Add in some existing config, like appDir, since they can be + //used inside the configFile -- paths and baseUrl are + //relative to them. + if (config.appDir && !mainConfig.appDir) { + mainConfig.appDir = config.appDir; + } + + //If no baseUrl, then use the directory holding the main config. + if (!mainConfig.baseUrl) { + mainConfig.baseUrl = mainConfigPath; + } + + build.makeAbsConfig(mainConfig, mainConfigPath); + mixConfig(config, mainConfig); + } + }); + } + + //Mix in build file config, but only after mainConfig has been mixed in. + //Since this is a re-application, skip array merging. + if (buildFileConfig) { + mixConfig(config, buildFileConfig, true); + } + + //Re-apply the override config values. Command line + //args should take precedence over build file values. + //Since this is a re-application, skip array merging. + mixConfig(config, cfg, true); + + //Fix paths to full paths so that they can be adjusted consistently + //lately to be in the output area. + lang.eachProp(config.paths, function (value, prop) { + if (lang.isArray(value)) { + throw new Error('paths fallback not supported in optimizer. ' + + 'Please provide a build config path override ' + + 'for ' + prop); + } + config.paths[prop] = build.makeAbsPath(value, config.baseUrl); + }); + + //Set final output dir + if (hasProp(config, "baseUrl")) { + if (config.appDir) { + if (!config.originalBaseUrl) { + throw new Error('Please set a baseUrl in the build config'); + } + config.dirBaseUrl = build.makeAbsPath(config.originalBaseUrl, config.dir); + } else { + config.dirBaseUrl = config.dir || config.baseUrl; + } + //Make sure dirBaseUrl ends in a slash, since it is + //concatenated with other strings. + config.dirBaseUrl = endsWithSlash(config.dirBaseUrl); + } + + if (config.bundlesConfigOutFile) { + if (!config.dir) { + throw new Error('bundlesConfigOutFile can only be used with optimizations ' + + 'that use "dir".'); + } + config.bundlesConfigOutFile = build.makeAbsPath(config.bundlesConfigOutFile, config.dir); + } + + //If out=stdout, write output to STDOUT instead of a file. + if (config.out && config.out === 'stdout') { + config.out = function (content) { + var e = env.get(); + if (e === 'rhino') { + var out = new java.io.PrintStream(java.lang.System.out, true, 'UTF-8'); + out.println(content); + } else if (e === 'node') { + process.stdout.write(content, 'utf8'); + } else { + console.log(content); + } + }; + } + + //Check for errors in config + if (config.main) { + throw new Error('"main" passed as an option, but the ' + + 'supported option is called "name".'); + } + if (config.out && !config.name && !config.modules && !config.include && + !config.cssIn) { + throw new Error('Missing either a "name", "include" or "modules" ' + + 'option'); + } + if (config.cssIn) { + if (config.dir || config.appDir) { + throw new Error('cssIn is only for the output of single file ' + + 'CSS optimizations and is not compatible with "dir" or "appDir" configuration.'); + } + if (!config.out) { + throw new Error('"out" option missing.'); + } + } + if (!config.cssIn && !config.baseUrl) { + //Just use the current directory as the baseUrl + config.baseUrl = './'; + } + if (!config.out && !config.dir) { + throw new Error('Missing either an "out" or "dir" config value. ' + + 'If using "appDir" for a full project optimization, ' + + 'use "dir". If you want to optimize to one file, ' + + 'use "out".'); + } + if (config.appDir && config.out) { + throw new Error('"appDir" is not compatible with "out". Use "dir" ' + + 'instead. appDir is used to copy whole projects, ' + + 'where "out" with "baseUrl" is used to just ' + + 'optimize to one file.'); + } + if (config.out && config.dir) { + throw new Error('The "out" and "dir" options are incompatible.' + + ' Use "out" if you are targeting a single file' + + ' for optimization, and "dir" if you want the appDir' + + ' or baseUrl directories optimized.'); + } + + + if (config.dir) { + // Make sure the output dir is not set to a parent of the + // source dir or the same dir, as it will result in source + // code deletion. + if (!config.allowSourceOverwrites && (config.dir === config.baseUrl || + config.dir === config.appDir || + (config.baseUrl && build.makeRelativeFilePath(config.dir, + config.baseUrl).indexOf('..') !== 0) || + (config.appDir && + build.makeRelativeFilePath(config.dir, config.appDir).indexOf('..') !== 0))) { + throw new Error('"dir" is set to a parent or same directory as' + + ' "appDir" or "baseUrl". This can result in' + + ' the deletion of source code. Stopping. If' + + ' you want to allow possible overwriting of' + + ' source code, set "allowSourceOverwrites"' + + ' to true in the build config, but do so at' + + ' your own risk. In that case, you may want' + + ' to also set "keepBuildDir" to true.'); + } + } + + if (config.insertRequire && !lang.isArray(config.insertRequire)) { + throw new Error('insertRequire should be a list of module IDs' + + ' to insert in to a require([]) call.'); + } + + //Support older configs with uglify2 settings, but now that uglify1 has + //been removed, just translate it to 'uglify' settings. + if (config.optimize === 'uglify2') { + config.optimize = 'uglify'; + } + if (config.uglify2) { + config.uglify = config.uglify2; + delete config.uglify2; + } + + if (config.generateSourceMaps) { + if (config.preserveLicenseComments && !(config.optimize === 'none' || config.optimize === 'uglify')) { + throw new Error('Cannot use preserveLicenseComments and ' + + 'generateSourceMaps together, unless optimize is set ' + + 'to \'uglify\'. Either explicitly set preserveLicenseComments ' + + 'to false (default is true) or turn off generateSourceMaps. ' + + 'If you want source maps with license comments, see: ' + + 'http://requirejs.org/docs/errors.html#sourcemapcomments'); + } else if (config.optimize !== 'none' && + config.optimize !== 'closure' && + config.optimize !== 'uglify') { + //Allow optimize: none to pass, since it is useful when toggling + //minification on and off to debug something, and it implicitly + //works, since it does not need a source map. + throw new Error('optimize: "' + config.optimize + + '" does not support generateSourceMaps.'); + } + } + + if ((config.name || config.include) && !config.modules) { + //Just need to build one file, but may be part of a whole appDir/ + //baseUrl copy, but specified on the command line, so cannot do + //the modules array setup. So create a modules section in that + //case. + config.modules = [ + { + name: config.name, + out: config.out, + create: config.create, + include: config.include, + exclude: config.exclude, + excludeShallow: config.excludeShallow, + insertRequire: config.insertRequire, + stubModules: config.stubModules + } + ]; + delete config.stubModules; + } else if (config.modules && config.out) { + throw new Error('If the "modules" option is used, then there ' + + 'should be a "dir" option set and "out" should ' + + 'not be used since "out" is only for single file ' + + 'optimization output.'); + } else if (config.modules && config.name) { + throw new Error('"name" and "modules" options are incompatible. ' + + 'Either use "name" if doing a single file ' + + 'optimization, or "modules" if you want to target ' + + 'more than one file for optimization.'); + } + + if (config.out && !config.cssIn) { + //Just one file to optimize. + + //Does not have a build file, so set up some defaults. + //Optimizing CSS should not be allowed, unless explicitly + //asked for on command line. In that case the only task is + //to optimize a CSS file. + if (!cfg.optimizeCss) { + config.optimizeCss = "none"; + } + } + + //Normalize cssPrefix + if (config.cssPrefix) { + //Make sure cssPrefix ends in a slash + config.cssPrefix = endsWithSlash(config.cssPrefix); + } else { + config.cssPrefix = ''; + } + + //Cycle through modules and normalize + if (config.modules && config.modules.length) { + config.modules.forEach(function (mod) { + if (lang.isArray(mod) || typeof mod === 'string' || !mod) { + throw new Error('modules config item is malformed: it should' + + ' be an object with a \'name\' property.'); + } + + //Combine any local stubModules with global values. + if (config.stubModules) { + mod.stubModules = config.stubModules.concat(mod.stubModules || []); + } + + //Create a hash lookup for the stubModules config to make lookup + //cheaper later. + if (mod.stubModules) { + mod.stubModules._byName = {}; + mod.stubModules.forEach(function (id) { + mod.stubModules._byName[id] = true; + }); + } + + // Legacy command support, which allowed a single string ID + // for include. + if (typeof mod.include === 'string') { + mod.include = [mod.include]; + } + + //Allow wrap config in overrides, but normalize it. + if (mod.override) { + normalizeWrapConfig(mod.override, absFilePath); + } + }); + } + + normalizeWrapConfig(config, absFilePath); + + //Do final input verification + if (config.context) { + throw new Error('The build argument "context" is not supported' + + ' in a build. It should only be used in web' + + ' pages.'); + } + + //Set up normalizeDirDefines. If not explicitly set, if optimize "none", + //set to "skip" otherwise set to "all". + if (!hasProp(config, 'normalizeDirDefines')) { + if (config.optimize === 'none' || config.skipDirOptimize) { + config.normalizeDirDefines = 'skip'; + } else { + config.normalizeDirDefines = 'all'; + } + } + + //Set file.fileExclusionRegExp if desired + if (hasProp(config, 'fileExclusionRegExp')) { + if (typeof config.fileExclusionRegExp === "string") { + file.exclusionRegExp = new RegExp(config.fileExclusionRegExp); + } else { + file.exclusionRegExp = config.fileExclusionRegExp; + } + } else if (hasProp(config, 'dirExclusionRegExp')) { + //Set file.dirExclusionRegExp if desired, this is the old + //name for fileExclusionRegExp before 1.0.2. Support for backwards + //compatibility + file.exclusionRegExp = config.dirExclusionRegExp; + } + + //Track the deps, but in a different key, so that they are not loaded + //as part of config seeding before all config is in play (#648). Was + //going to merge this in with "include", but include is added after + //the "name" target. To preserve what r.js has done previously, make + //sure "deps" comes before the "name". + if (config.deps) { + config._depsInclude = config.deps; + } + + + //Remove things that may cause problems in the build. + //deps already merged above + delete config.deps; + delete config.jQuery; + delete config.enforceDefine; + delete config.urlArgs; + + return config; + }; + + /** + * finds the module being built/optimized with the given moduleName, + * or returns null. + * @param {String} moduleName + * @param {Array} modules + * @returns {Object} the module object from the build profile, or null. + */ + build.findBuildModule = function (moduleName, modules) { + var i, module; + for (i = 0; i < modules.length; i++) { + module = modules[i]; + if (module.name === moduleName) { + return module; + } + } + return null; + }; + + /** + * Removes a module name and path from a layer, if it is supposed to be + * excluded from the layer. + * @param {String} moduleName the name of the module + * @param {String} path the file path for the module + * @param {Object} layer the layer to remove the module/path from + */ + build.removeModulePath = function (module, path, layer) { + var index = layer.buildFilePaths.indexOf(path); + if (index !== -1) { + layer.buildFilePaths.splice(index, 1); + } + }; + + /** + * Uses the module build config object to trace the dependencies for the + * given module. + * + * @param {Object} module the module object from the build config info. + * @param {Object} config the build config object. + * @param {Object} [baseLoaderConfig] the base loader config to use for env resets. + * + * @returns {Object} layer information about what paths and modules should + * be in the flattened module. + */ + build.traceDependencies = function (module, config, baseLoaderConfig) { + var include, override, layer, context, oldContext, + rawTextByIds, + syncChecks = { + rhino: true, + node: true, + xpconnect: true + }, + deferred = prim(); + + //Reset some state set up in requirePatch.js, and clean up require's + //current context. + oldContext = require._buildReset(); + + //Grab the reset layer and context after the reset, but keep the + //old config to reuse in the new context. + layer = require._layer; + context = layer.context; + + //Put back basic config, use a fresh object for it. + if (baseLoaderConfig) { + require(copyConfig(baseLoaderConfig)); + } + + logger.trace("\nTracing dependencies for: " + (module.name || + (typeof module.out === 'function' ? 'FUNCTION' : module.out))); + include = config._depsInclude || []; + include = include.concat(module.name && !module.create ? [module.name] : []); + if (module.include) { + include = include.concat(module.include); + } + + //If there are overrides to basic config, set that up now.; + if (module.override) { + if (baseLoaderConfig) { + override = build.createOverrideConfig(baseLoaderConfig, module.override); + } else { + override = copyConfig(module.override); + } + require(override); + } + + //Now, populate the rawText cache with any values explicitly passed in + //via config. + rawTextByIds = require.s.contexts._.config.rawText; + if (rawTextByIds) { + lang.eachProp(rawTextByIds, function (contents, id) { + var url = require.toUrl(id) + '.js'; + require._cachedRawText[url] = contents; + }); + } + + + //Configure the callbacks to be called. + deferred.reject.__requireJsBuild = true; + + //Use a wrapping function so can check for errors. + function includeFinished(value) { + //If a sync build environment, check for errors here, instead of + //in the then callback below, since some errors, like two IDs pointed + //to same URL but only one anon ID will leave the loader in an + //unresolved state since a setTimeout cannot be used to check for + //timeout. + var hasError = false; + if (syncChecks[env.get()]) { + try { + build.checkForErrors(context, layer); + } catch (e) { + hasError = true; + deferred.reject(e); + } + } + + if (!hasError) { + deferred.resolve(value); + } + } + includeFinished.__requireJsBuild = true; + + //Figure out module layer dependencies by calling require to do the work. + require(include, includeFinished, deferred.reject); + + // If a sync env, then with the "two IDs to same anon module path" + // issue, the require never completes, need to check for errors + // here. + if (syncChecks[env.get()]) { + build.checkForErrors(context, layer); + } + + return deferred.promise.then(function () { + //Reset config + if (module.override && baseLoaderConfig) { + require(copyConfig(baseLoaderConfig)); + } + + build.checkForErrors(context, layer); + + return layer; + }); + }; + + build.checkForErrors = function (context, layer) { + //Check to see if it all loaded. If not, then throw, and give + //a message on what is left. + var id, prop, mod, idParts, pluginId, pluginResources, + errMessage = '', + failedPluginMap = {}, + failedPluginIds = [], + errIds = [], + errUrlMap = {}, + errUrlConflicts = {}, + hasErrUrl = false, + hasUndefined = false, + defined = context.defined, + registry = context.registry; + + function populateErrUrlMap(id, errUrl, skipNew) { + // Loader plugins do not have an errUrl, so skip them. + if (!errUrl) { + return; + } + + if (!skipNew) { + errIds.push(id); + } + + if (errUrlMap[errUrl]) { + hasErrUrl = true; + //This error module has the same URL as another + //error module, could be misconfiguration. + if (!errUrlConflicts[errUrl]) { + errUrlConflicts[errUrl] = []; + //Store the original module that had the same URL. + errUrlConflicts[errUrl].push(errUrlMap[errUrl]); + } + errUrlConflicts[errUrl].push(id); + } else if (!skipNew) { + errUrlMap[errUrl] = id; + } + } + + for (id in registry) { + if (hasProp(registry, id) && id.indexOf('_@r') !== 0) { + hasUndefined = true; + mod = getOwn(registry, id); + idParts = id.split('!'); + pluginId = idParts[0]; + + if (id.indexOf('_unnormalized') === -1 && mod && mod.enabled) { + populateErrUrlMap(id, mod.map.url); + } + + //Look for plugins that did not call load() + //But skip plugin IDs that were already inlined and called + //define() with a name. + if (!hasProp(layer.modulesWithNames, id) && idParts.length > 1) { + if (falseProp(failedPluginMap, pluginId)) { + failedPluginIds.push(pluginId); + } + pluginResources = failedPluginMap[pluginId]; + if (!pluginResources) { + pluginResources = failedPluginMap[pluginId] = []; + } + pluginResources.push(id + (mod.error ? ': ' + mod.error : '')); + } + } + } + + // If have some modules that are not defined/stuck in the registry, + // then check defined modules for URL overlap. + if (hasUndefined) { + for (id in defined) { + if (hasProp(defined, id) && id.indexOf('!') === -1) { + populateErrUrlMap(id, require.toUrl(id) + '.js', true); + } + } + } + + if (errIds.length || failedPluginIds.length) { + if (failedPluginIds.length) { + errMessage += 'Loader plugin' + + (failedPluginIds.length === 1 ? '' : 's') + + ' did not call ' + + 'the load callback in the build:\n' + + failedPluginIds.map(function (pluginId) { + var pluginResources = failedPluginMap[pluginId]; + return pluginId + ':\n ' + pluginResources.join('\n '); + }).join('\n') + '\n'; + } + errMessage += 'Module loading did not complete for: ' + errIds.join(', '); + + if (hasErrUrl) { + errMessage += '\nThe following modules share the same URL. This ' + + 'could be a misconfiguration if that URL only has ' + + 'one anonymous module in it:'; + for (prop in errUrlConflicts) { + if (hasProp(errUrlConflicts, prop)) { + errMessage += '\n' + prop + ': ' + + errUrlConflicts[prop].join(', '); + } + } + } + throw new Error(errMessage); + } + }; + + build.createOverrideConfig = function (config, override) { + var cfg = copyConfig(config), + oride = copyConfig(override); + + lang.eachProp(oride, function (value, prop) { + if (hasProp(build.objProps, prop)) { + //An object property, merge keys. Start a new object + //so that source object in config does not get modified. + cfg[prop] = {}; + lang.mixin(cfg[prop], config[prop], true); + lang.mixin(cfg[prop], override[prop], true); + } else { + cfg[prop] = override[prop]; + } + }); + + return cfg; + }; + + /** + * Uses the module build config object to create an flattened version + * of the module, with deep dependencies included. + * + * @param {Object} module the module object from the build config info. + * + * @param {Object} layer the layer object returned from build.traceDependencies. + * + * @param {Object} the build config object. + * + * @returns {Object} with two properties: "text", the text of the flattened + * module, and "buildText", a string of text representing which files were + * included in the flattened module text. + */ + build.flattenModule = function (module, layer, config) { + var fileContents, sourceMapGenerator, + sourceMapBase, + buildFileContents = ''; + + return prim().start(function () { + var reqIndex, currContents, fileForSourceMap, + moduleName, shim, packageName, + parts, builder, writeApi, + namespace, namespaceWithDot, stubModulesByName, + context = layer.context, + onLayerEnds = [], + onLayerEndAdded = {}, + pkgsMainMap = {}; + + //Use override settings, particularly for pragmas + //Do this before the var readings since it reads config values. + if (module.override) { + config = build.createOverrideConfig(config, module.override); + } + + namespace = config.namespace || ''; + namespaceWithDot = namespace ? namespace + '.' : ''; + stubModulesByName = (module.stubModules && module.stubModules._byName) || {}; + + //Start build output for the module. + module.onCompleteData = { + name: module.name, + path: (config.dir ? module._buildPath.replace(config.dir, "") : module._buildPath), + included: [] + }; + + buildFileContents += "\n" + + module.onCompleteData.path + + "\n----------------\n"; + + //If there was an existing file with require in it, hoist to the top. + if (layer.existingRequireUrl) { + reqIndex = layer.buildFilePaths.indexOf(layer.existingRequireUrl); + if (reqIndex !== -1) { + layer.buildFilePaths.splice(reqIndex, 1); + layer.buildFilePaths.unshift(layer.existingRequireUrl); + } + } + + if (config.generateSourceMaps) { + sourceMapBase = config.dir || config.baseUrl; + if (module._buildPath === 'FUNCTION') { + fileForSourceMap = (module.name || module.include[0] || 'FUNCTION') + '.build.js'; + } else if (config.out) { + fileForSourceMap = module._buildPath.split('/').pop(); + } else { + fileForSourceMap = module._buildPath.replace(sourceMapBase, ''); + } + sourceMapGenerator = new SourceMapGenerator({ + file: fileForSourceMap + }); + } + + //Create a reverse lookup for packages main module IDs to their package + //names, useful for knowing when to write out define() package main ID + //adapters. + lang.eachProp(layer.context.config.pkgs, function(value, prop) { + pkgsMainMap[value] = prop; + }); + + //Write the built module to disk, and build up the build output. + fileContents = ""; + if (config.wrap && config.wrap.__startMap) { + config.wrap.__startMap.forEach(function (wrapFunction) { + fileContents = wrapFunction(fileContents, config, sourceMapGenerator); + }); + } + + return prim.serial(layer.buildFilePaths.map(function (path) { + return function () { + var singleContents = ''; + + moduleName = layer.buildFileToModule[path]; + + //If the moduleName is a package main, then hold on to the + //packageName in case an adapter needs to be written. + packageName = getOwn(pkgsMainMap, moduleName); + + return prim().start(function () { + //Figure out if the module is a result of a build plugin, and if so, + //then delegate to that plugin. + parts = context.makeModuleMap(moduleName); + builder = parts.prefix && getOwn(context.defined, parts.prefix); + if (builder) { + if (builder.onLayerEnd && falseProp(onLayerEndAdded, parts.prefix)) { + onLayerEnds.push(builder); + onLayerEndAdded[parts.prefix] = true; + } + + if (builder.write) { + writeApi = function (input) { + singleContents += "\n" + addSemiColon(input, config); + if (config.onBuildWrite) { + singleContents = config.onBuildWrite(moduleName, path, singleContents); + } + }; + writeApi.asModule = function (moduleName, input) { + singleContents += "\n" + + addSemiColon(build.toTransport(namespace, moduleName, path, input, layer, { + useSourceUrl: layer.context.config.useSourceUrl + }), config); + if (config.onBuildWrite) { + singleContents = config.onBuildWrite(moduleName, path, singleContents); + } + }; + builder.write(parts.prefix, parts.name, writeApi); + } + return; + } else { + return prim().start(function () { + if (hasProp(stubModulesByName, moduleName)) { + //Just want to insert a simple module definition instead + //of the source module. Useful for plugins that inline + //all their resources. + if (hasProp(layer.context.plugins, moduleName)) { + //Slightly different content for plugins, to indicate + //that dynamic loading will not work. + return 'define({load: function(id){throw new Error("Dynamic load not allowed: " + id);}});'; + } else { + return 'define({});'; + } + } else { + return require._cacheReadAsync(path); + } + }).then(function (text) { + var hasPackageName; + + currContents = text; + + if (config.cjsTranslate && + (!config.shim || !lang.hasProp(config.shim, moduleName))) { + currContents = commonJs.convert(path, currContents); + } + + if (config.onBuildRead) { + currContents = config.onBuildRead(moduleName, path, currContents); + } + + if (packageName) { + hasPackageName = (packageName === parse.getNamedDefine(currContents)); + } + + if (namespace) { + currContents = pragma.namespace(currContents, namespace); + } + + currContents = build.toTransport(namespace, moduleName, path, currContents, layer, { + useSourceUrl: config.useSourceUrl + }); + + if (packageName && !hasPackageName) { + currContents = addSemiColon(currContents, config) + '\n'; + currContents += namespaceWithDot + "define('" + + packageName + "', ['" + moduleName + + "'], function (main) { return main; });\n"; + } + + if (config.onBuildWrite) { + currContents = config.onBuildWrite(moduleName, path, currContents); + } + + //Semicolon is for files that are not well formed when + //concatenated with other content. + singleContents += addSemiColon(currContents, config); + }); + } + }).then(function () { + var shimDeps, shortPath = path.replace(config.dir, ""); + + module.onCompleteData.included.push(shortPath); + buildFileContents += shortPath + "\n"; + + //Some files may not have declared a require module, and if so, + //put in a placeholder call so the require does not try to load them + //after the module is processed. + //If we have a name, but no defined module, then add in the placeholder. + if (moduleName && falseProp(layer.modulesWithNames, moduleName) && !config.skipModuleInsertion) { + shim = config.shim && (getOwn(config.shim, moduleName) || (packageName && getOwn(config.shim, packageName))); + if (shim) { + shimDeps = lang.isArray(shim) ? shim : shim.deps; + if (config.wrapShim) { + + singleContents = '(function(root) {\n' + + namespaceWithDot + 'define("' + moduleName + '", ' + + (shimDeps && shimDeps.length ? + build.makeJsArrayString(shimDeps) + ', ' : '[], ') + + 'function() {\n' + + ' return (function() {\n' + + singleContents + + // Start with a \n in case last line is a comment + // in the singleContents, like a sourceURL comment. + '\n' + (shim.exportsFn ? shim.exportsFn() : '') + + '\n' + + ' }).apply(root, arguments);\n' + + '});\n' + + '}(this));\n'; + } else { + singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", ' + + (shimDeps && shimDeps.length ? + build.makeJsArrayString(shimDeps) + ', ' : '') + + (shim.exportsFn ? shim.exportsFn() : 'function(){}') + + ');\n'; + } + } else { + singleContents += '\n' + namespaceWithDot + 'define("' + moduleName + '", function(){});\n'; + } + } + + //Add line break at end of file, instead of at beginning, + //so source map line numbers stay correct, but still allow + //for some space separation between files in case ASI issues + //for concatenation would cause an error otherwise. + singleContents += '\n'; + + //Add to the source map and to the final contents + fileContents = appendToFileContents(fileContents, singleContents, path, config, module, + sourceMapGenerator); + }); + }; + })).then(function () { + if (onLayerEnds.length) { + onLayerEnds.forEach(function (builder, index) { + var path; + if (typeof module.out === 'string') { + path = module.out; + } else if (typeof module._buildPath === 'string') { + path = module._buildPath; + } + builder.onLayerEnd(function (input) { + fileContents = + appendToFileContents(fileContents, "\n" + addSemiColon(input, config), + 'onLayerEnd' + index + '.js', config, module, sourceMapGenerator); + }, { + name: module.name, + path: path + }); + }); + } + + if (module.create) { + //The ID is for a created layer. Write out + //a module definition for it in case the + //built file is used with enforceDefine + //(#432) + fileContents = + appendToFileContents(fileContents, '\n' + namespaceWithDot + 'define("' + module.name + + '", function(){});\n', 'module-create.js', config, module, + sourceMapGenerator); + } + + //Add a require at the end to kick start module execution, if that + //was desired. Usually this is only specified when using small shim + //loaders like almond. + if (module.insertRequire) { + fileContents = + appendToFileContents(fileContents, '\n' + namespaceWithDot + 'require(["' + module.insertRequire.join('", "') + + '"]);\n', 'module-insertRequire.js', config, module, + sourceMapGenerator); + } + }); + }).then(function () { + if (config.wrap && config.wrap.__endMap) { + config.wrap.__endMap.forEach(function (wrapFunction) { + fileContents = wrapFunction(fileContents, config, sourceMapGenerator); + }); + } + return { + text: fileContents, + buildText: buildFileContents, + sourceMap: sourceMapGenerator ? + JSON.stringify(sourceMapGenerator.toJSON(), null, ' ') : + undefined + }; + }); + }; + + //Converts an JS array of strings to a string representation. + //Not using JSON.stringify() for Rhino's sake. + build.makeJsArrayString = function (ary) { + return '["' + ary.map(function (item) { + //Escape any double quotes, backslashes + return lang.jsEscape(item); + }).join('","') + '"]'; + }; + + build.toTransport = function (namespace, moduleName, path, contents, layer, options) { + var baseUrl = layer && layer.context.config.baseUrl; + + function onFound(info) { + //Only mark this module as having a name if not a named module, + //or if a named module and the name matches expectations. + if (layer && (info.needsId || info.foundId === moduleName)) { + layer.modulesWithNames[moduleName] = true; + } + } + + //Convert path to be a local one to the baseUrl, useful for + //useSourceUrl. + if (baseUrl) { + path = path.replace(baseUrl, ''); + } + + return transform.toTransport(namespace, moduleName, path, contents, onFound, options); + }; + + return build; +}); + + } + + + /** + * Sets the default baseUrl for requirejs to be directory of top level + * script. + */ + function setBaseUrl(fileName) { + //Use the file name's directory as the baseUrl if available. + dir = fileName.replace(/\\/g, '/'); + if (dir.indexOf('/') !== -1) { + dir = dir.split('/'); + dir.pop(); + dir = dir.join('/'); + //Make sure dir is JS-escaped, since it will be part of a JS string. + exec("require({baseUrl: '" + dir.replace(/[\\"']/g, '\\$&') + "'});"); + } + } + + function createRjsApi() { + //Create a method that will run the optimzer given an object + //config. + requirejs.optimize = function (config, callback, errback) { + if (!loadedOptimizedLib) { + loadLib(); + loadedOptimizedLib = true; + } + + //Create the function that will be called once build modules + //have been loaded. + var runBuild = function (build, logger, quit) { + //Make sure config has a log level, and if not, + //make it "silent" by default. + config.logLevel = config.hasOwnProperty('logLevel') ? + config.logLevel : logger.SILENT; + + //Reset build internals first in case this is part + //of a long-running server process that could have + //exceptioned out in a bad state. It is only defined + //after the first call though. + if (requirejs._buildReset) { + requirejs._buildReset(); + requirejs._cacheReset(); + } + + function done(result) { + //And clean up, in case something else triggers + //a build in another pathway. + if (requirejs._buildReset) { + requirejs._buildReset(); + requirejs._cacheReset(); + } + + // Ensure errors get propagated to the errback + if (result instanceof Error) { + throw result; + } + + return result; + } + + errback = errback || function (err) { + // Using console here since logger may have + // turned off error logging. Since quit is + // called want to be sure a message is printed. + console.log(err); + quit(1); + }; + + build(config).then(done, done).then(callback, errback); + }; + + requirejs({ + context: 'build' + }, ['build', 'logger', 'env!env/quit'], runBuild); + }; + + requirejs.tools = { + useLib: function (contextName, callback) { + if (!callback) { + callback = contextName; + contextName = 'uselib'; + } + + if (!useLibLoaded[contextName]) { + loadLib(); + useLibLoaded[contextName] = true; + } + + var req = requirejs({ + context: contextName + }); + + req(['build'], function () { + callback(req); + }); + } + }; + + requirejs.define = define; + } + + //If in Node, and included via a require('requirejs'), just export and + //THROW IT ON THE GROUND! + if (env === 'node' && reqMain !== module) { + setBaseUrl(path.resolve(reqMain ? reqMain.filename : '.')); + + createRjsApi(); + + module.exports = requirejs; + return; + } else if (env === 'browser') { + //Only option is to use the API. + setBaseUrl(location.href); + createRjsApi(); + return; + } else if ((env === 'rhino' || env === 'xpconnect') && + //User sets up requirejsAsLib variable to indicate it is loaded + //via load() to be used as a library. + typeof requirejsAsLib !== 'undefined' && requirejsAsLib) { + //This script is loaded via rhino's load() method, expose the + //API and get out. + setBaseUrl(fileName); + createRjsApi(); + return; + } + + if (commandOption === 'o') { + //Do the optimizer work. + loadLib(); + + /* + * Create a build.js file that has the build options you want and pass that + * build file to this file to do the build. See example.build.js for more information. + */ + +/*jslint strict: false, nomen: false */ +/*global require: false */ + +require({ + baseUrl: require.s.contexts._.config.baseUrl, + //Use a separate context than the default context so that the + //build can use the default context. + context: 'build', + catchError: { + define: true + } +}, ['env!env/args', 'env!env/quit', 'logger', 'build'], +function (args, quit, logger, build) { + build(args).then(function () {}, function (err) { + logger.error(err); + quit(1); + }); +}); + + + } else if (commandOption === 'v') { + console.log('r.js: ' + version + + ', RequireJS: ' + this.requirejsVars.require.version + + ', UglifyJS: 2.8.29'); + } else if (commandOption === 'convert') { + loadLib(); + + this.requirejsVars.require(['env!env/args', 'commonJs', 'env!env/print'], + function (args, commonJs, print) { + + var srcDir, outDir; + srcDir = args[0]; + outDir = args[1]; + + if (!srcDir || !outDir) { + print('Usage: path/to/commonjs/modules output/dir'); + return; + } + + commonJs.convertDir(args[0], args[1]); + }); + } else { + //Just run an app + + //Load the bundled libraries for use in the app. + if (commandOption === 'lib') { + loadLib(); + } + + setBaseUrl(fileName); + + if (exists(fileName)) { + exec(readFile(fileName), fileName); + } else { + showHelp(); + } + } + +}((typeof console !== 'undefined' ? console : undefined), + (typeof Packages !== 'undefined' || (typeof window === 'undefined' && + typeof Components !== 'undefined' && Components.interfaces) ? + Array.prototype.slice.call(arguments, 0) : []), + (typeof readFile !== 'undefined' ? readFile : undefined))); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/require.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/require.js new file mode 100644 index 0000000000000000000000000000000000000000..857eb5b700075e95bb3660352da06bd2c117ab86 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/require.js @@ -0,0 +1,36 @@ +/* + RequireJS 2.2.0 Copyright jQuery Foundation and other contributors. + Released under MIT license, http://github.com/requirejs/requirejs/LICENSE +*/ +var requirejs,require,define; +(function(ga){function ka(b,c,d,g){return g||""}function K(b){return"[object Function]"===Q.call(b)}function L(b){return"[object Array]"===Q.call(b)}function y(b,c){if(b){var d;for(d=0;d<b.length&&(!b[d]||!c(b[d],d,b));d+=1);}}function X(b,c){if(b){var d;for(d=b.length-1;-1<d&&(!b[d]||!c(b[d],d,b));--d);}}function x(b,c){return la.call(b,c)}function e(b,c){return x(b,c)&&b[c]}function D(b,c){for(var d in b)if(x(b,d)&&c(b[d],d))break}function Y(b,c,d,g){c&&D(c,function(c,e){if(d||!x(b,e))!g||"object"!== +typeof c||!c||L(c)||K(c)||c instanceof RegExp?b[e]=c:(b[e]||(b[e]={}),Y(b[e],c,d,g))});return b}function z(b,c){return function(){return c.apply(b,arguments)}}function ha(b){throw b;}function ia(b){if(!b)return b;var c=ga;y(b.split("."),function(b){c=c[b]});return c}function F(b,c,d,g){c=Error(c+"\nhttp://requirejs.org/docs/errors.html#"+b);c.requireType=b;c.requireModules=g;d&&(c.originalError=d);return c}function ma(b){function c(a,n,b){var h,k,f,c,d,l,g,r;n=n&&n.split("/");var q=p.map,m=q&&q["*"]; +if(a){a=a.split("/");k=a.length-1;p.nodeIdCompat&&U.test(a[k])&&(a[k]=a[k].replace(U,""));"."===a[0].charAt(0)&&n&&(k=n.slice(0,n.length-1),a=k.concat(a));k=a;for(f=0;f<k.length;f++)c=k[f],"."===c?(k.splice(f,1),--f):".."===c&&0!==f&&(1!==f||".."!==k[2])&&".."!==k[f-1]&&0<f&&(k.splice(f-1,2),f-=2);a=a.join("/")}if(b&&q&&(n||m)){k=a.split("/");f=k.length;a:for(;0<f;--f){d=k.slice(0,f).join("/");if(n)for(c=n.length;0<c;--c)if(b=e(q,n.slice(0,c).join("/")))if(b=e(b,d)){h=b;l=f;break a}!g&&m&&e(m,d)&& +(g=e(m,d),r=f)}!h&&g&&(h=g,l=r);h&&(k.splice(0,l,h),a=k.join("/"))}return(h=e(p.pkgs,a))?h:a}function d(a){E&&y(document.getElementsByTagName("script"),function(n){if(n.getAttribute("data-requiremodule")===a&&n.getAttribute("data-requirecontext")===l.contextName)return n.parentNode.removeChild(n),!0})}function m(a){var n=e(p.paths,a);if(n&&L(n)&&1<n.length)return n.shift(),l.require.undef(a),l.makeRequire(null,{skipMap:!0})([a]),!0}function r(a){var n,b=a?a.indexOf("!"):-1;-1<b&&(n=a.substring(0, +b),a=a.substring(b+1,a.length));return[n,a]}function q(a,n,b,h){var k,f,d=null,g=n?n.name:null,p=a,q=!0,m="";a||(q=!1,a="_@r"+(Q+=1));a=r(a);d=a[0];a=a[1];d&&(d=c(d,g,h),f=e(v,d));a&&(d?m=f&&f.normalize?f.normalize(a,function(a){return c(a,g,h)}):-1===a.indexOf("!")?c(a,g,h):a:(m=c(a,g,h),a=r(m),d=a[0],m=a[1],b=!0,k=l.nameToUrl(m)));b=!d||f||b?"":"_unnormalized"+(T+=1);return{prefix:d,name:m,parentMap:n,unnormalized:!!b,url:k,originalName:p,isDefine:q,id:(d?d+"!"+m:m)+b}}function u(a){var b=a.id, +c=e(t,b);c||(c=t[b]=new l.Module(a));return c}function w(a,b,c){var h=a.id,k=e(t,h);if(!x(v,h)||k&&!k.defineEmitComplete)if(k=u(a),k.error&&"error"===b)c(k.error);else k.on(b,c);else"defined"===b&&c(v[h])}function A(a,b){var c=a.requireModules,h=!1;if(b)b(a);else if(y(c,function(b){if(b=e(t,b))b.error=a,b.events.error&&(h=!0,b.emit("error",a))}),!h)g.onError(a)}function B(){V.length&&(y(V,function(a){var b=a[0];"string"===typeof b&&(l.defQueueMap[b]=!0);G.push(a)}),V=[])}function C(a){delete t[a]; +delete Z[a]}function J(a,b,c){var h=a.map.id;a.error?a.emit("error",a.error):(b[h]=!0,y(a.depMaps,function(h,f){var d=h.id,g=e(t,d);!g||a.depMatched[f]||c[d]||(e(b,d)?(a.defineDep(f,v[d]),a.check()):J(g,b,c))}),c[h]=!0)}function H(){var a,b,c=(a=1E3*p.waitSeconds)&&l.startTime+a<(new Date).getTime(),h=[],k=[],f=!1,g=!0;if(!aa){aa=!0;D(Z,function(a){var l=a.map,e=l.id;if(a.enabled&&(l.isDefine||k.push(a),!a.error))if(!a.inited&&c)m(e)?f=b=!0:(h.push(e),d(e));else if(!a.inited&&a.fetched&&l.isDefine&& +(f=!0,!l.prefix))return g=!1});if(c&&h.length)return a=F("timeout","Load timeout for modules: "+h,null,h),a.contextName=l.contextName,A(a);g&&y(k,function(a){J(a,{},{})});c&&!b||!f||!E&&!ja||ba||(ba=setTimeout(function(){ba=0;H()},50));aa=!1}}function I(a){x(v,a[0])||u(q(a[0],null,!0)).init(a[1],a[2])}function O(a){a=a.currentTarget||a.srcElement;var b=l.onScriptLoad;a.detachEvent&&!ca?a.detachEvent("onreadystatechange",b):a.removeEventListener("load",b,!1);b=l.onScriptError;a.detachEvent&&!ca||a.removeEventListener("error", +b,!1);return{node:a,id:a&&a.getAttribute("data-requiremodule")}}function P(){var a;for(B();G.length;){a=G.shift();if(null===a[0])return A(F("mismatch","Mismatched anonymous define() module: "+a[a.length-1]));I(a)}l.defQueueMap={}}var aa,da,l,R,ba,p={waitSeconds:7,baseUrl:"./",paths:{},bundles:{},pkgs:{},shim:{},config:{}},t={},Z={},ea={},G=[],v={},W={},fa={},Q=1,T=1;R={require:function(a){return a.require?a.require:a.require=l.makeRequire(a.map)},exports:function(a){a.usingExports=!0;if(a.map.isDefine)return a.exports? +v[a.map.id]=a.exports:a.exports=v[a.map.id]={}},module:function(a){return a.module?a.module:a.module={id:a.map.id,uri:a.map.url,config:function(){return e(p.config,a.map.id)||{}},exports:a.exports||(a.exports={})}}};da=function(a){this.events=e(ea,a.id)||{};this.map=a;this.shim=e(p.shim,a.id);this.depExports=[];this.depMaps=[];this.depMatched=[];this.pluginMaps={};this.depCount=0};da.prototype={init:function(a,b,c,h){h=h||{};if(!this.inited){this.factory=b;if(c)this.on("error",c);else this.events.error&& +(c=z(this,function(a){this.emit("error",a)}));this.depMaps=a&&a.slice(0);this.errback=c;this.inited=!0;this.ignore=h.ignore;h.enabled||this.enabled?this.enable():this.check()}},defineDep:function(a,b){this.depMatched[a]||(this.depMatched[a]=!0,--this.depCount,this.depExports[a]=b)},fetch:function(){if(!this.fetched){this.fetched=!0;l.startTime=(new Date).getTime();var a=this.map;if(this.shim)l.makeRequire(this.map,{enableBuildCallback:!0})(this.shim.deps||[],z(this,function(){return a.prefix?this.callPlugin(): +this.load()}));else return a.prefix?this.callPlugin():this.load()}},load:function(){var a=this.map.url;W[a]||(W[a]=!0,l.load(this.map.id,a))},check:function(){if(this.enabled&&!this.enabling){var a,b,c=this.map.id;b=this.depExports;var h=this.exports,k=this.factory;if(!this.inited)x(l.defQueueMap,c)||this.fetch();else if(this.error)this.emit("error",this.error);else if(!this.defining){this.defining=!0;if(1>this.depCount&&!this.defined){if(K(k)){if(this.events.error&&this.map.isDefine||g.onError!== +ha)try{h=l.execCb(c,k,b,h)}catch(d){a=d}else h=l.execCb(c,k,b,h);this.map.isDefine&&void 0===h&&((b=this.module)?h=b.exports:this.usingExports&&(h=this.exports));if(a)return a.requireMap=this.map,a.requireModules=this.map.isDefine?[this.map.id]:null,a.requireType=this.map.isDefine?"define":"require",A(this.error=a)}else h=k;this.exports=h;if(this.map.isDefine&&!this.ignore&&(v[c]=h,g.onResourceLoad)){var f=[];y(this.depMaps,function(a){f.push(a.normalizedMap||a)});g.onResourceLoad(l,this.map,f)}C(c); +this.defined=!0}this.defining=!1;this.defined&&!this.defineEmitted&&(this.defineEmitted=!0,this.emit("defined",this.exports),this.defineEmitComplete=!0)}}},callPlugin:function(){var a=this.map,b=a.id,d=q(a.prefix);this.depMaps.push(d);w(d,"defined",z(this,function(h){var k,f,d=e(fa,this.map.id),M=this.map.name,r=this.map.parentMap?this.map.parentMap.name:null,m=l.makeRequire(a.parentMap,{enableBuildCallback:!0});if(this.map.unnormalized){if(h.normalize&&(M=h.normalize(M,function(a){return c(a,r,!0)})|| +""),f=q(a.prefix+"!"+M,this.map.parentMap),w(f,"defined",z(this,function(a){this.map.normalizedMap=f;this.init([],function(){return a},null,{enabled:!0,ignore:!0})})),h=e(t,f.id)){this.depMaps.push(f);if(this.events.error)h.on("error",z(this,function(a){this.emit("error",a)}));h.enable()}}else d?(this.map.url=l.nameToUrl(d),this.load()):(k=z(this,function(a){this.init([],function(){return a},null,{enabled:!0})}),k.error=z(this,function(a){this.inited=!0;this.error=a;a.requireModules=[b];D(t,function(a){0=== +a.map.id.indexOf(b+"_unnormalized")&&C(a.map.id)});A(a)}),k.fromText=z(this,function(h,c){var d=a.name,f=q(d),M=S;c&&(h=c);M&&(S=!1);u(f);x(p.config,b)&&(p.config[d]=p.config[b]);try{g.exec(h)}catch(e){return A(F("fromtexteval","fromText eval for "+b+" failed: "+e,e,[b]))}M&&(S=!0);this.depMaps.push(f);l.completeLoad(d);m([d],k)}),h.load(a.name,m,k,p))}));l.enable(d,this);this.pluginMaps[d.id]=d},enable:function(){Z[this.map.id]=this;this.enabling=this.enabled=!0;y(this.depMaps,z(this,function(a, +b){var c,h;if("string"===typeof a){a=q(a,this.map.isDefine?this.map:this.map.parentMap,!1,!this.skipMap);this.depMaps[b]=a;if(c=e(R,a.id)){this.depExports[b]=c(this);return}this.depCount+=1;w(a,"defined",z(this,function(a){this.undefed||(this.defineDep(b,a),this.check())}));this.errback?w(a,"error",z(this,this.errback)):this.events.error&&w(a,"error",z(this,function(a){this.emit("error",a)}))}c=a.id;h=t[c];x(R,c)||!h||h.enabled||l.enable(a,this)}));D(this.pluginMaps,z(this,function(a){var b=e(t,a.id); +b&&!b.enabled&&l.enable(a,this)}));this.enabling=!1;this.check()},on:function(a,b){var c=this.events[a];c||(c=this.events[a]=[]);c.push(b)},emit:function(a,b){y(this.events[a],function(a){a(b)});"error"===a&&delete this.events[a]}};l={config:p,contextName:b,registry:t,defined:v,urlFetched:W,defQueue:G,defQueueMap:{},Module:da,makeModuleMap:q,nextTick:g.nextTick,onError:A,configure:function(a){a.baseUrl&&"/"!==a.baseUrl.charAt(a.baseUrl.length-1)&&(a.baseUrl+="/");if("string"===typeof a.urlArgs){var b= +a.urlArgs;a.urlArgs=function(a,c){return(-1===c.indexOf("?")?"?":"&")+b}}var c=p.shim,h={paths:!0,bundles:!0,config:!0,map:!0};D(a,function(a,b){h[b]?(p[b]||(p[b]={}),Y(p[b],a,!0,!0)):p[b]=a});a.bundles&&D(a.bundles,function(a,b){y(a,function(a){a!==b&&(fa[a]=b)})});a.shim&&(D(a.shim,function(a,b){L(a)&&(a={deps:a});!a.exports&&!a.init||a.exportsFn||(a.exportsFn=l.makeShimExports(a));c[b]=a}),p.shim=c);a.packages&&y(a.packages,function(a){var b;a="string"===typeof a?{name:a}:a;b=a.name;a.location&& +(p.paths[b]=a.location);p.pkgs[b]=a.name+"/"+(a.main||"main").replace(na,"").replace(U,"")});D(t,function(a,b){a.inited||a.map.unnormalized||(a.map=q(b,null,!0))});(a.deps||a.callback)&&l.require(a.deps||[],a.callback)},makeShimExports:function(a){return function(){var b;a.init&&(b=a.init.apply(ga,arguments));return b||a.exports&&ia(a.exports)}},makeRequire:function(a,n){function m(c,d,f){var e,r;n.enableBuildCallback&&d&&K(d)&&(d.__requireJsBuild=!0);if("string"===typeof c){if(K(d))return A(F("requireargs", +"Invalid require call"),f);if(a&&x(R,c))return R[c](t[a.id]);if(g.get)return g.get(l,c,a,m);e=q(c,a,!1,!0);e=e.id;return x(v,e)?v[e]:A(F("notloaded",'Module name "'+e+'" has not been loaded yet for context: '+b+(a?"":". Use require([])")))}P();l.nextTick(function(){P();r=u(q(null,a));r.skipMap=n.skipMap;r.init(c,d,f,{enabled:!0});H()});return m}n=n||{};Y(m,{isBrowser:E,toUrl:function(b){var d,f=b.lastIndexOf("."),g=b.split("/")[0];-1!==f&&("."!==g&&".."!==g||1<f)&&(d=b.substring(f,b.length),b=b.substring(0, +f));return l.nameToUrl(c(b,a&&a.id,!0),d,!0)},defined:function(b){return x(v,q(b,a,!1,!0).id)},specified:function(b){b=q(b,a,!1,!0).id;return x(v,b)||x(t,b)}});a||(m.undef=function(b){B();var c=q(b,a,!0),f=e(t,b);f.undefed=!0;d(b);delete v[b];delete W[c.url];delete ea[b];X(G,function(a,c){a[0]===b&&G.splice(c,1)});delete l.defQueueMap[b];f&&(f.events.defined&&(ea[b]=f.events),C(b))});return m},enable:function(a){e(t,a.id)&&u(a).enable()},completeLoad:function(a){var b,c,d=e(p.shim,a)||{},g=d.exports; +for(B();G.length;){c=G.shift();if(null===c[0]){c[0]=a;if(b)break;b=!0}else c[0]===a&&(b=!0);I(c)}l.defQueueMap={};c=e(t,a);if(!b&&!x(v,a)&&c&&!c.inited)if(!p.enforceDefine||g&&ia(g))I([a,d.deps||[],d.exportsFn]);else return m(a)?void 0:A(F("nodefine","No define call for "+a,null,[a]));H()},nameToUrl:function(a,b,c){var d,k,f,m;(d=e(p.pkgs,a))&&(a=d);if(d=e(fa,a))return l.nameToUrl(d,b,c);if(g.jsExtRegExp.test(a))d=a+(b||"");else{d=p.paths;k=a.split("/");for(f=k.length;0<f;--f)if(m=k.slice(0,f).join("/"), +m=e(d,m)){L(m)&&(m=m[0]);k.splice(0,f,m);break}d=k.join("/");d+=b||(/^data\:|^blob\:|\?/.test(d)||c?"":".js");d=("/"===d.charAt(0)||d.match(/^[\w\+\.\-]+:/)?"":p.baseUrl)+d}return p.urlArgs&&!/^blob\:/.test(d)?d+p.urlArgs(a,d):d},load:function(a,b){g.load(l,a,b)},execCb:function(a,b,c,d){return b.apply(d,c)},onScriptLoad:function(a){if("load"===a.type||oa.test((a.currentTarget||a.srcElement).readyState))N=null,a=O(a),l.completeLoad(a.id)},onScriptError:function(a){var b=O(a);if(!m(b.id)){var c=[]; +D(t,function(a,d){0!==d.indexOf("_@r")&&y(a.depMaps,function(a){if(a.id===b.id)return c.push(d),!0})});return A(F("scripterror",'Script error for "'+b.id+(c.length?'", needed by: '+c.join(", "):'"'),a,[b.id]))}}};l.require=l.makeRequire();return l}function pa(){if(N&&"interactive"===N.readyState)return N;X(document.getElementsByTagName("script"),function(b){if("interactive"===b.readyState)return N=b});return N}var g,B,C,H,O,I,N,P,u,T,qa=/(\/\*([\s\S]*?)\*\/|([^:]|^)\/\/(.*)$)/mg,ra=/[^.]\s*require\s*\(\s*["']([^'"\s]+)["']\s*\)/g, +U=/\.js$/,na=/^\.\//;B=Object.prototype;var Q=B.toString,la=B.hasOwnProperty,E=!("undefined"===typeof window||"undefined"===typeof navigator||!window.document),ja=!E&&"undefined"!==typeof importScripts,oa=E&&"PLAYSTATION 3"===navigator.platform?/^complete$/:/^(complete|loaded)$/,ca="undefined"!==typeof opera&&"[object Opera]"===opera.toString(),J={},w={},V=[],S=!1;if("undefined"===typeof define){if("undefined"!==typeof requirejs){if(K(requirejs))return;w=requirejs;requirejs=void 0}"undefined"===typeof require|| +K(require)||(w=require,require=void 0);g=requirejs=function(b,c,d,m){var r,q="_";L(b)||"string"===typeof b||(r=b,L(c)?(b=c,c=d,d=m):b=[]);r&&r.context&&(q=r.context);(m=e(J,q))||(m=J[q]=g.s.newContext(q));r&&m.configure(r);return m.require(b,c,d)};g.config=function(b){return g(b)};g.nextTick="undefined"!==typeof setTimeout?function(b){setTimeout(b,4)}:function(b){b()};require||(require=g);g.version="2.2.0";g.jsExtRegExp=/^\/|:|\?|\.js$/;g.isBrowser=E;B=g.s={contexts:J,newContext:ma};g({});y(["toUrl", +"undef","defined","specified"],function(b){g[b]=function(){var c=J._;return c.require[b].apply(c,arguments)}});E&&(C=B.head=document.getElementsByTagName("head")[0],H=document.getElementsByTagName("base")[0])&&(C=B.head=H.parentNode);g.onError=ha;g.createNode=function(b,c,d){c=b.xhtml?document.createElementNS("http://www.w3.org/1999/xhtml","html:script"):document.createElement("script");c.type=b.scriptType||"text/javascript";c.charset="utf-8";c.async=!0;return c};g.load=function(b,c,d){var m=b&&b.config|| +{},e;if(E){e=g.createNode(m,c,d);e.setAttribute("data-requirecontext",b.contextName);e.setAttribute("data-requiremodule",c);!e.attachEvent||e.attachEvent.toString&&0>e.attachEvent.toString().indexOf("[native code")||ca?(e.addEventListener("load",b.onScriptLoad,!1),e.addEventListener("error",b.onScriptError,!1)):(S=!0,e.attachEvent("onreadystatechange",b.onScriptLoad));e.src=d;if(m.onNodeCreated)m.onNodeCreated(e,m,c,d);P=e;H?C.insertBefore(e,H):C.appendChild(e);P=null;return e}if(ja)try{setTimeout(function(){}, +0),importScripts(d),b.completeLoad(c)}catch(q){b.onError(F("importscripts","importScripts failed for "+c+" at "+d,q,[c]))}};E&&!w.skipDataMain&&X(document.getElementsByTagName("script"),function(b){C||(C=b.parentNode);if(O=b.getAttribute("data-main"))return u=O,w.baseUrl||-1!==u.indexOf("!")||(I=u.split("/"),u=I.pop(),T=I.length?I.join("/")+"/":"./",w.baseUrl=T),u=u.replace(U,""),g.jsExtRegExp.test(u)&&(u=O),w.deps=w.deps?w.deps.concat(u):[u],!0});define=function(b,c,d){var e,g;"string"!==typeof b&& +(d=c,c=b,b=null);L(c)||(d=c,c=null);!c&&K(d)&&(c=[],d.length&&(d.toString().replace(qa,ka).replace(ra,function(b,d){c.push(d)}),c=(1===d.length?["require"]:["require","exports","module"]).concat(c)));S&&(e=P||pa())&&(b||(b=e.getAttribute("data-requiremodule")),g=J[e.getAttribute("data-requirecontext")]);g?(g.defQueue.push([b,c,d]),g.defQueueMap[b]=!0):V.push([b,c,d])};define.amd={jQuery:!0};g.exec=function(b){return eval(b)};g(w)}})(this); diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/udpRepeater.js b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/udpRepeater.js new file mode 100644 index 0000000000000000000000000000000000000000..1f8aac571cd0856e75fcc240f93373267e1527ed --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/scripts/udpRepeater.js @@ -0,0 +1,32 @@ +//set UDP listener +var PORT = 1415; +var HOST = 'localhost'; + +var dgram = require('dgram'); +var server = dgram.createSocket('udp4'); + +//set up WebSocket repeater +const WebSocket = require('ws'); + +const websocket = new WebSocket('ws://track.movesinstitute.org:80'); + +websocket.onopen = function(evt){console.log("Opened websocket");};//console.log("websocket onopen");}; +websocket.onclose = function(evt){console.log("websocket close", evt);}; +websocket.onerror = function(evt){console.log("websocket error", evt.data);}; + + + +//turn on udp listener +server.on('listening', function () { + var address = server.address(); + console.log('UDP Server listening on ' + address.address + ":" + address.port); +}); +//when a message is recieved, echo it to the websocket +server.on('message', function (message, remote) { + console.log(remote.address + ':' + remote.port +' - ' + message); + websocket.send(message); + +}); + +server.bind(PORT, HOST); + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tank.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tank.png new file mode 100644 index 0000000000000000000000000000000000000000..460254529fe8218f7fbafd7166f11513fcfdb11e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tank.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tankBig.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tankBig.png new file mode 100644 index 0000000000000000000000000000000000000000..0c57c57a68d057bcdf277f23515d88b7c8f6bcd9 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/Final Project2/tankBig.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/ReadMe.txt b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/ReadMe.txt new file mode 100644 index 0000000000000000000000000000000000000000..f835f03db60c0d84790e2e58df6048015975b77b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/FinalProjects/SasalaMaroon/ReadMe.txt @@ -0,0 +1,16 @@ +Final Project Notes: + +CSVreaderOpenDisEspduSender.java takes LTC Brian Hanley's program +(HanleyOpenDisEspduSender.java) and modifies it to send out UDP datagram +packets. BLUF the program reads in a CSV file packages it into a DIS packet +and sends that out via a UDP socket. + +udpRepeater.js is a node.js file that captures UDP packets and forwards them to +ws://track.movesinstitute.org:80 +To run you will need to download Node.js from https://nodejs.org/en/ +as well as the websocket module from https://github.com/websockets/ws +run it in terminal. + +googleMaps.html is a modified version of DMcG's example. Moved the map to +center on Monterey and changed the markers to reflect images of the passed +units diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment 1.pptx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment 1.pptx new file mode 100644 index 0000000000000000000000000000000000000000..103e13c1be9660acc2b57074827e248f630fe35d Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment 1.pptx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment1ConsoleUML.pptx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment1ConsoleUML.pptx new file mode 100644 index 0000000000000000000000000000000000000000..103e13c1be9660acc2b57074827e248f630fe35d Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelAssignment1ConsoleUML.pptx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelClient.java new file mode 100644 index 0000000000000000000000000000000000000000..6a0e37d58b2ead379cb95dab13516e8aa03797bc --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelClient.java @@ -0,0 +1,74 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +// no package required or desired, use Netbeans menu item "Run File +import java.io.*; +import java.net.*; +/** + * + * @author cs2017 + */ +public class AngelClient { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) + { + boolean operate = true; + + while (operate) + { + + try + { + System.out.println("creating socket"); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket("localhost", 2317); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); + if ("Exit".equals(serverMessage)){ + System.out.println("The server has asked to shut the client down."); + operate = false; + } + else { + int spd = Integer.parseInt(br.readLine()); + int x = Integer.parseInt(br.readLine()); + int y = Integer.parseInt(br.readLine()); + int z = Integer.parseInt(br.readLine()); + String lastCommand = br.readLine(); + AngelTank tank = new AngelTank(serverMessage, spd, new int[]{x, y, z}); + + System.out.println(serverMessage+" is traveling at "+spd+" with position ("+x+", "+y+", "+z+")."); + if ("Exit".equals(lastCommand)){ + System.out.println("The server has asked to shut the client down."); + operate = false; + } + } + } + catch(IOException e) + { + System.out.println(e); + System.out.println("Problem with client"); + } + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelServer.java new file mode 100644 index 0000000000000000000000000000000000000000..3bc98c4ca7a71f185be6474284336c9ec1d56923 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelServer.java @@ -0,0 +1,85 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +// no package required or desired, use Netbeans menu item "Run File" +import java.io.*; +import java.net.*; +/** + * + * @author cs2017 + */ +public class AngelServer { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + // TODO code application logic here + boolean goforit = true; + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + ServerSocket serverSocket = new ServerSocket(2317); + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(goforit) + { + Socket clientConnection = serverSocket.accept(); + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.println("Abrams 1"); + ps.println(60); + ps.println(152); + ps.println(25); + ps.println(30); + + ps.println("Exit"); + + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking"); + } + + } + +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelTank.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelTank.java new file mode 100644 index 0000000000000000000000000000000000000000..c20c8d01b053e28c7b827885b33d3c1a14d35363 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/AngelTank.java @@ -0,0 +1,50 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +// no package required or desired, Netbeans will automatically compile + +/** + * + * @author cs2017 + */ +public class AngelTank { + + private String type; + private int speed; + private int[] position; + + AngelTank(String type, int i, int[] pos) { + + this.type = type; + this.speed = i; + this.position = pos; + + } + + /** + * @return the type + */ + public String getType() { + return type; + } + + /** + * @return the speed + */ + public int getSpeed() { + return speed; + } + + /** + * @return the position + */ + public int[] getPosition() { + return position; + } + + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbeckerConsoleOutput.txt b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbeckerConsoleOutput.txt new file mode 100644 index 0000000000000000000000000000000000000000..c35183aa3565b58c6a1b7eed48a21552b546d80c --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbeckerConsoleOutput.txt @@ -0,0 +1,13 @@ +Subject: HW console output +From:"Blankenbeker, Michael (Capt)" <mjblanke@nps.edu> + +Console output for HW shows the following: + +client class: +creating socket +The message the server sent was This was written by the server + +server class: +The message the client sent was This response was written by myTcpClient +Socket pair: (( /127.0.0.1, 2317 ), ( /127.0.0.1, 56950 )) +Connection count is: 1 diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..0391b6f01d957f6e10689eb9d9abdfac9ee575ed --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpClient.java @@ -0,0 +1,72 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +//package mv3500code; +import java.io.*; +import java.net.*; + +/** + * Before, we always used telnet to connect to the server. We + * are now writing our own program to do the connection. + * + * As you will see, when we run this after we start the server + * we will see the same string telnet printed, sent by the server. + * The output at the server will show different socket pairs for + * each time we ran it. + * + * @author mcgredo + */ +public class BlankenbekerMyTcpClient { + + + public static void main(String[] args) + { + try + { + while(true){ + + + System.out.println("creating socket"); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket("localhost", 2317); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); + System.out.println("The message the server sent was " + serverMessage); + + OutputStream os = socket.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("This response was written by myTcpClient"); // to remote client + + + // "flush()" in important in that it forces a write + // across what is in fact a slow connection + ps.flush(); + + } + } + catch(IOException e) + { + System.out.println(e); + System.out.println("Problem with client :" + e); + } + System.out.println("client exit"); + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..0f9f3fe7e054a10aa69ebb187926d0841fc06084 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/BlankenbekerMyTcpServer.java @@ -0,0 +1,97 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package mv3500code; + +import java.io.*; +import java.net.*; + +/** + * Very slightly more complex than example1. A complete copy of + * example 2. The only thing this does + * differently is introduce a loop into the response, so you don't + * have to restart the program after one response. Also, it prints + * out the socket pair the server sees. Run the program via telnet + * several times and compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer + * while running this program. + * + * telnet <ipOfServersLaptop> 2317 + * + * And have him display the socket pairs he got. + * @author mcgredo + */ +public class BlankenbekerMyTcpServer +{ + + public static void main(String[] args) + { + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + int connectionCount = 0; + ServerSocket serverSocket = new ServerSocket(2317); + Socket clientConnection = serverSocket.accept(); + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(true) + { + + + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + connectionCount++; + ps.println("This was written by the server"); + + InputStream is = clientConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); + System.out.println("The message the client sent was " + serverMessage); + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + System.out.println("Connection count is: " + connectionCount); + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking"); + } + + } + + + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardScreenShot2018-02-14.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardScreenShot2018-02-14.png new file mode 100644 index 0000000000000000000000000000000000000000..d162ad756570f423039de26591303d596910489b Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardScreenShot2018-02-14.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardUML.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardUML.pdf new file mode 100644 index 0000000000000000000000000000000000000000..8501d6d0a9b927dd372b89b481d2d6633ee322fa Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/ConardUML.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyHomework1ConsoleLogs.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyHomework1ConsoleLogs.docx new file mode 100644 index 0000000000000000000000000000000000000000..9d2b935e1477f1dcecd6d720dabc06b894c67237 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyHomework1ConsoleLogs.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..0a1232189da6d2c311d3c2b27423e135ba4047bb --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpClient.java @@ -0,0 +1,64 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +//package Homework1; + +import java.io.*; +import java.net.*; + +/** + * + * @author Brian + */ +public class HanleyTcpClient { + public static void main(String[] args) + { + try + { + System.out.println("creating socket"); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket("localhost", 2317); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); + System.out.println("1 The message the server sent was " + serverMessage); + + // Outgoing Messages + OutputStream os = socket.getOutputStream(); + PrintStream ps = new PrintStream(os); + ps.println("bbb report: X, Y, X " + System.currentTimeMillis()); + + serverMessage = br.readLine(); + System.out.println("2 The message the server sent was " + serverMessage); + + //os = socket.getOutputStream(); + // ps = new PrintStream(os); + ps.println("Final message from client " + System.currentTimeMillis()); + serverMessage = br.readLine(); + System.out.println("3 The message the server sent was " + serverMessage); + + + } + catch(Exception e) + { + System.out.println(e); + System.out.println("Problem with client"); + } + + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..f54711e6e5d83ccc3d702d44f434f9b61774e847 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyTcpServer.java @@ -0,0 +1,106 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package Homework1; + + +import java.io.*; +import java.net.*; + + + +/** + * + * @author Brian + */ +public class HanleyTcpServer { + +/** + * Very slightly more complex than example1. A complete copy of + * example 2. The only thing this does + * differently is introduce a loop into the response, so you don't + * have to restart the program after one response. Also, it prints + * out the socket pair the server sees. Run the program via telnet + * several times and compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer + * while running this program. + * + * telnet <ipOfServersLaptop> 2317 + * + * And have him display the socket pairs he got. + * @author mcgredo + */ + public static void main(String[] args) + { + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + ServerSocket serverSocket = new ServerSocket(2317); + Socket clientConnection = serverSocket.accept(); + + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(true) + { + //Socket clientConnection = serverSocket.accept(); + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("This was written by the server"); + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + //Exchange of Data + InputStream is = clientConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String clientMessage = br.readLine(); + + if (clientMessage.startsWith("loc")){ + System.out.println("Location Report \n"+ clientMessage); + } + else System.out.println("Incoming Message \n" + clientMessage); + ps.println("Message received"); + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking"); + } + + } + +} + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyUmlDrawingHomework1.vsdx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyUmlDrawingHomework1.vsdx new file mode 100644 index 0000000000000000000000000000000000000000..5e1b7182e7a5b79f0e6274747f5af0fb2173f4ba Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/HanleyUmlDrawingHomework1.vsdx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasAssignment01_ConsoleOutput.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasAssignment01_ConsoleOutput.pdf new file mode 100644 index 0000000000000000000000000000000000000000..8b43977fec2e46f3248f2e4cdb3a219d8958a7b0 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasAssignment01_ConsoleOutput.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient1.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient1.java new file mode 100644 index 0000000000000000000000000000000000000000..75c31bbad7ec299cd4d9b4606ee42d89637635ba --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient1.java @@ -0,0 +1,51 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package MV3500Cohort2018JanuaryMarch.homework1; + +import java.io.*; +import java.net.*; + +/** + * + * @author Rico + */ +public class LandasClient1 { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + + try + { + System.out.println("Creating Socket"); + Socket cs = new Socket("localhost", 2317); + + while (true) { + + PrintStream cp = new PrintStream(cs.getOutputStream()); + System.out.print("\nClient: \n"); + System.out.print("Please enter entity identifier and position: "); + InputStreamReader cir = new InputStreamReader(System.in); + BufferedReader cbr = new BufferedReader(cir); + String temp1 = cbr.readLine(); + cp.println(temp1); + BufferedReader cbr1 = new BufferedReader(new InputStreamReader(cs.getInputStream())); + String temp2 = cbr1.readLine(); + System.out.print(temp2); + + } + } + catch(Exception e) + { + System.out.println(e); + System.out.println(" Problem with client"); + + } + + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient2.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient2.java new file mode 100644 index 0000000000000000000000000000000000000000..fe7d94857ce10622ed66b4a3b6740d928fa06391 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasClient2.java @@ -0,0 +1,66 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package MV3500Cohort2018JanuaryMarch.homework1; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.Scanner; +/** + * + * @author Rico + */ +public class LandasClient2 { + + public static DataInputStream in; + public static DataOutputStream out; + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + // TODO code application logic here + //declare a scanner so we can write a message + Scanner keyboard = new Scanner(System.in); + + // localhost ip + String ip = "127.0.0.1"; + int port = 2317; + Socket socket; + + try { + + //connect + socket = new Socket(ip, port); + + //initialize streams + //DataInputStream in = new DataInputStream(socket.getInputStream()); + //DataOutputStream out = new DataOutputStream(socket.getOutputStream()); + in = new DataInputStream(socket.getInputStream()); + out = new DataOutputStream(socket.getOutputStream()); + + + while (true){ + System.out.print("\nMessage to server: "); + //Write a message + String message = keyboard.nextLine(); + //Send it to the server which will print it and send a confirmation + out.writeUTF(message); + + // recieve the incoming messages and print + String message2 = in.readUTF(); + System.out.println(message2); + } + + } + catch(IOException e) { + System.out.println(e); + System.out.println("\nProblem with client"); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer1.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer1.java new file mode 100644 index 0000000000000000000000000000000000000000..67e2a543d754237aa075dc4df3b787f5ee4b5415 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer1.java @@ -0,0 +1,55 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package MV3500Cohort2018JanuaryMarch.homework1; + +import java.io.*; +import java.net.*; + +/** + * + * @author Rico + */ +public class LandasServer1 { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + + try + { + ServerSocket ss = new ServerSocket(2317); + + while(true) { + + Socket cs = ss.accept(); + BufferedReader cbr = new BufferedReader(new InputStreamReader(cs.getInputStream())); + String temp = cbr.readLine(); + //System.out.println("Client:" + temp); + //JOptionPane.showMessageDialog(null,"Salam"); + PrintStream spr = new PrintStream(cs.getOutputStream()); + String temp1 = "Server: I got your message: " + temp; + spr.println(temp1); + //server(); + + } + + + } + catch(Exception e) { + System.out.println("problem with networking"); + } + + + + + + + + + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer2.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer2.java new file mode 100644 index 0000000000000000000000000000000000000000..c42b8a82a67d38e1d58a2e1361b8b88d78d27c34 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasServer2.java @@ -0,0 +1,68 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package MV3500Cohort2018JanuaryMarch.homework1; + +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; + + +/** + * + * @author Rico + */ +public class LandasServer2 { + + public static DataInputStream in; + public static DataOutputStream out; + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + // TODO code application logic here + int port = 2317; + ServerSocket server; + Socket clientSocket; + + try { + + //start listening on port + server = new ServerSocket(port); + + System.out.println("Listening on port: " + port); + + //Accept client + clientSocket = server.accept(); + + System.out.println("Client Connected!"); + + //initialize streams so we can send message + in = new DataInputStream(clientSocket.getInputStream()); + out = new DataOutputStream(clientSocket.getOutputStream()); + + String message; + + while (true) { + + // as soon as a message is being received, print it out! + message = in.readUTF(); + System.out.println("Server received: " + message); + // send a message confirmation to the client + String temp1 = "Server: I received your message of " + "'" + message + "'"; + out.writeUTF(temp1); + + } + + } + catch(IOException e) { + System.out.println("problem with networking: " + e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasUML_Assignment1.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasUML_Assignment1.pdf new file mode 100644 index 0000000000000000000000000000000000000000..d38baf3080d78e8ea1cab33d804bbff53c35d13f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/LandasUML_Assignment1.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonHomework1UML.pptx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonHomework1UML.pptx new file mode 100644 index 0000000000000000000000000000000000000000..2d92f878296ebf46e4e039d9b84157254780b1d6 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonHomework1UML.pptx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..d4cba73960565370c080a5baec4869aab9c742e7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpClient.java @@ -0,0 +1,64 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + + +//package tcpclient; + +import java.io.*; +import java.net.*; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.Socket; +import java.util.Scanner; + +/** + * Before, we always used telnet to connect to the server. We + * are now writing our own program to do the connection. + * + * As you will see, when we run this after we start the server + * we will see the same string telnet printed, sent by the server. + * The output at the server will show different socket pairs for + * each time we ran it. + * + * @author mcgredo + */ +public class MaroonTcpClient { + + public static DataInputStream input; + public static DataOutputStream output; + + + + public static void main(String[] args) + { + Scanner userInput = new Scanner(System.in); + try + { + System.out.println("creating socket"); + Socket socket = new Socket("localhost", 2317); + + input = new DataInputStream(socket.getInputStream()); + output = new DataOutputStream(socket.getOutputStream()); + + + + System.out.println("Type position or ID: \n "); + String request; + request = userInput.nextLine(); + output.writeUTF(request); + + String reply; + reply = input.readUTF(); + System.out.println(reply); + + + } + catch(Exception e) + { + System.out.println(e); + System.out.println("Problem with client"); + } + + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..9b0d5731e8473aef4e9e73efcb9fc1d5a10598f8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonTcpServer.java @@ -0,0 +1,89 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package tcpserver; + +import java.io.*; +import java.net.*; +import java.io.DataInputStream; +import java.io.DataOutputStream; +import java.io.IOException; +import java.net.ServerSocket; +import java.net.Socket; +import java.util.Arrays; + +/** + * Very slightly more complex than example1. A complete copy of + * example 2. The only thing this does + * differently is introduce a loop into the response, so you don't + * have to restart the program after one response. Also, it prints + * out the socket pair the server sees. Run the program via telnet + * several times and compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer + * while running this program. + * + * telnet <ipOfServersLaptop> 2317 + * + * And have him display the socket pairs he got. + * @author mcgredo + */ +public class MaroonTcpServer +{ + + public static DataInputStream input; + public static DataOutputStream output; + + + public static void main(String[] args) + { + + MaroonUnit testUnit1 = new MaroonUnit (); + + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + ServerSocket serverSocket = new ServerSocket(2317); + + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(true) + { + Socket clientConnection = serverSocket.accept(); + //OutputStream os = clientConnection.getOutputStream(); + input = new DataInputStream(clientConnection.getInputStream()); + output = new DataOutputStream(clientConnection.getOutputStream()); + + String request = input.readUTF(); + request = request.trim(); // get rid of outer whitespace + + if ("position".equalsIgnoreCase(request)){ + output.writeUTF(Arrays.toString(testUnit1.getPosition())); + } + else if ("ID".equalsIgnoreCase(request)){ + output.writeUTF(""+ testUnit1.getID()); + + }else + output.writeUTF("I don't understand, try www.google.com"); + + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking"); + } + + } + +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonUnit.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonUnit.java new file mode 100644 index 0000000000000000000000000000000000000000..613e903aebddef677e3b0691bc66c1c46bd4c453 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MaroonUnit.java @@ -0,0 +1,45 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +//package tcpserver; + +/** + * + * @author Kens + */ +class MaroonUnit { + + private int[] position = new int[3]; + private int ID; + + MaroonUnit() { + this.position[0] = 0; + this.position[1] = 0; + this.position[2] = 0; + + this.ID = 50; + + } + + MaroonUnit(int x, int y, int z, int id){ + this.position[0] = x; + this.position[1] = y; + this.position[2] = z; + + this.ID = id; + } + + int getID(){ + return this.ID; + } + + int [] getPosition(){ + return this.position; + } + + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MyMulticastSender b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/MyMulticastSender new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaClient.java new file mode 100644 index 0000000000000000000000000000000000000000..55c6653d8f65f30783ffc0b1d8844176e52fb6f0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaClient.java @@ -0,0 +1,47 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package Assignment01; + +import java.io.*; +import java.net.*; +/** + * + * @author Jeremiah Sasala + */ +public class SasalaClient { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + // TODO code application logic here + while(true){ + try + { + System.out.println("-------------------------------------------------------------------"); + // from the server, instead of one only. + Socket socket = new Socket("127.0.0.1", 2317); + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage01 = br.readLine(); + String serverMessage02 = br.readLine(); + String serverMessage03 = br.readLine(); + String serverMessage04 = br.readLine(); + String serverMessage05 = br.readLine(); + + System.out.println("The message the server sent was . . . " + serverMessage01); + System.out.println("The message the server sent was . . . " + serverMessage02); + System.out.println("The message the server sent was . . . " + serverMessage03); + System.out.println("The message the server sent was . . . " + serverMessage04); + System.out.println("The message the server sent was . . . " + serverMessage05); + } + catch(Exception e) + { + System.out.println("Problem with client"); + System.out.println(e); + } + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaOutputConsole.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaOutputConsole.docx new file mode 100644 index 0000000000000000000000000000000000000000..fff905ec66545c6894bda877168155fd5a61095c Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaOutputConsole.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaServer.java new file mode 100644 index 0000000000000000000000000000000000000000..e048afe8f8c6cd90f9e70599ce72a20cd7fe89aa --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaServer.java @@ -0,0 +1,59 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package Assignment01; + +import java.io.*; +import java.net.*; +/** + * + * @author Jeremiah Sasala + */ +public class SasalaServer { + + /** + * @param args the command line arguments + */ + public static void main(String[] args) { + + try + { + + ServerSocket serverSocket = new ServerSocket(2317); + + while(true) + { + Socket clientConnection = serverSocket.accept(); + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + String entityName = "Ranger"; + double xPos = Math.round(Math.random()*10); + double yPos = Math.round(Math.random()*10); + double zPos = Math.round(Math.random()*10); + + ps.println("Entity position information"); + ps.println("Name: " + entityName); + ps.println("X coordinate: " + xPos); + ps.println("Y coordinate: " + yPos); + ps.println("Z coordinate: " + zPos); + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking: " + e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaUmlDiagram.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaUmlDiagram.docx new file mode 100644 index 0000000000000000000000000000000000000000..bed7502a55e7804be9a0e1f4bdd77bbd71811340 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SasalaUmlDiagram.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellConsoleOutput.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellConsoleOutput.png new file mode 100644 index 0000000000000000000000000000000000000000..4badd29f60cb8e49fb513dc7744f03a5a027e1e6 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellConsoleOutput.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellHW2UmlDiagram.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellHW2UmlDiagram.pdf new file mode 100644 index 0000000000000000000000000000000000000000..9185dd6a68fb098cc2a69338ad802537bbc10530 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellHW2UmlDiagram.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionClient.java new file mode 100644 index 0000000000000000000000000000000000000000..5c81461abc7a99611c16e4c72b023453d7943512 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionClient.java @@ -0,0 +1,41 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package PositionClient; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.io.PrintWriter; +import java.net.Socket; +import java.net.UnknownHostException; + +/** + * + * @author AJSNELL + */ +public class SnellPositionClient { + /** + * @param args the command line arguments + * @throws java.io.IOException + */ + public static void main(String[] args) throws IOException { + String hostName = args[0]; + try (Socket clientSocket = new Socket(hostName, 8005); + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream())); + BufferedReader stdIn = new BufferedReader(new InputStreamReader(System.in))) { + String userInput; + out.println("unit id: 1\nunit pos: 11S MS 4859 9849"); + while ((userInput = stdIn.readLine()) != null) { + out.println(userInput); + System.out.println("from client: " + in.readLine()); + } + } catch (UnknownHostException e) { + System.err.println("Don't know about host " + hostName); + System.exit(1); + } catch (IOException e) { + System.err.println("Couldn't get I/O for the connection to " + hostName); + System.exit(1); + } + } +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionServer.java new file mode 100644 index 0000000000000000000000000000000000000000..a4ec0eee09d1d80a1a1c812156f1fdb08c95955d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/SnellPositionServer.java @@ -0,0 +1,32 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package positionserver; + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStreamReader; +import java.net.ServerSocket; +import java.net.Socket; +import java.io.PrintWriter; + +public class SnellPositionServer { + /** + * @param args the command line arguments + * @throws java.io.IOException + */ + public static void main(String[] args) throws IOException { + try (ServerSocket serverSocket = new ServerSocket(8005); + Socket clientSocket = serverSocket.accept(); + PrintWriter out = new PrintWriter(clientSocket.getOutputStream(), true); + BufferedReader in = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));) { + System.out.println("Client connected on port 8005"); + String inputLine; + while ((inputLine = in.readLine()) != null) { + System.out.println("Received message: " + inputLine + " from " + clientSocket.toString()); + out.println(inputLine); + } + } catch (IOException e) { + System.out.println("Exception when trying to listen on port 8005"); + } + } +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..088ed611314aceca9e8d17e0df7da4dc00d56783 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpClient.java @@ -0,0 +1,86 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package tcpclient; +import java.net.Socket; + +import java.io.*; +import java.net.*; + +/** + * Before, we always used telnet to connect to the server. We are now writing + * our own program to do the connection. + * + * As you will see, when we run this after we start the server we will see the + * same string telnet printed, sent by the server. The output at the server will + * show different socket pairs for each time we ran it. + * + * @author mcgredo + */ +public class TackettTcpClient { + + public final static String LOCALHOST = "localhost"; + //String can also be IPV4 127.0.0.1 or IPV6 0:0:0:0:0:0:0:1 + + public static void main(String[] args) { + + try { + //while (true) { + System.out.println("creating socket"); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket(LOCALHOST, 2317); + + OutputStream os = socket.getOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(os); + BufferedWriter bw = new BufferedWriter(osw); + + String locationMessage = "Enemy infantry spotted in the open at position Alpha"; + + String sendMessage = locationMessage + "\n"; + bw.write(sendMessage); + bw.flush(); + System.out.println("Message sent to the server: " + sendMessage); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String message = br.readLine(); + System.out.println("Message received from the server: "+message); + + String serverMessage = br.readLine(); + System.out.println("Now we're talking"); + System.out.println("The message the server sent was " + serverMessage); + } + catch(Exception exception) + { + // System.out.println(e); + exception.printStackTrace(); + System.out.println("Problem with client"); + System.out.println(exception); + } + finally + { + try + { + //socket.close(); + } + catch(Exception e) + { + e.printStackTrace(); + } + } + System.out.println("client exit"); + } + } + + + + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..49d2f0c922bfdae964fb2a0e496a5ffbabc82da7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettTcpServer.java @@ -0,0 +1,104 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + +//package tcpserver; +import java.net.Socket; +import java.net.ServerSocket; + +import java.io.*; +import java.net.*; + +/** + * Very slightly more complex than example1. A complete copy of + * example 2. The only thing this does + * differently is introduce a loop into the response, so you don't + * have to restart the program after one response. Also, it prints + * out the socket pair the server sees. Run the program via telnet + * several times and compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer + * while running this program. + * + * telnet <ipOfServersLaptop> 2317 + * + * And have him display the socket pairs he got. + * @author mcgredo + */ +public class TackettTcpServer +{ + + public static void main(String[] args) + { + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + ServerSocket serverSocket = new ServerSocket(2317); + + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(true) + { + Socket clientConnection = serverSocket.accept(); + InputStream is = clientConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String receivedMessage = br.readLine(); + System.out.println("Message received from client is " + receivedMessage); + + String returnMessage; + + returnMessage = "Enemy position acknowledged" + "\n"; + + + OutputStream os = clientConnection.getOutputStream(); + OutputStreamWriter osw = new OutputStreamWriter(os); + BufferedWriter bw = new BufferedWriter(osw); + bw.write(returnMessage); + System.out.println("Message sent to the client is " + returnMessage); + bw.flush(); + + PrintStream ps = new PrintStream(os); + + ps.println("This was written by the server"); + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking"); + } + + } + +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettUmlDiagram.pptx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettUmlDiagram.pptx new file mode 100644 index 0000000000000000000000000000000000000000..b8a7b0ff57f16dcbebde4a4a6006eeb72fae5252 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/TackettUmlDiagram.pptx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraOutputs.png b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraOutputs.png new file mode 100644 index 0000000000000000000000000000000000000000..7f979a0d27544b621fd207fd152c2d919b16779e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraOutputs.png differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraSequenceDiagram.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraSequenceDiagram.docx new file mode 100644 index 0000000000000000000000000000000000000000..e209e4ff03f1af688dfdb9fb6942f1006581d54f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraSequenceDiagram.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..f443901647943551af137118c8e03ddfad86add6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpClient.java @@ -0,0 +1,82 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + + +import java.io.*; +import java.net.*; + +/** + * MV3500 + * + * TCP Client + * + * @author Douglas Yamashita de Moura + * @version 20180212 + * + */ +public class YamashitaDeMouraTcpClient { + + public static void main(String[] args) + { + try + { + boolean openConnection = true; + + Socket socket = new Socket("localhost", 2317); + + System.out.println("Socket created. Communication started...\n"); + + // Create entity + YamashitaDeMouraEntity entity = new YamashitaDeMouraEntity("Test Entity", 10, 20, 15); + String response = ""; + + int messageCount = 1; + + while(openConnection) { + + System.out.println("Request #" + messageCount); + + // Output + OutputStream os = socket.getOutputStream(); + PrintStream ps = new PrintStream(os); + + switch(messageCount) { + case 1: + response = "'Hi, I am the client and I request a connection.'\n"; + break; + case 2: + response = "'Sending entity with name " + entity.getName() + + " and position (" + entity.getX() + ", " + entity.getY() + + ", " + entity.getZ() + ").'\n"; + break; + case 3: + response = "'Thanks!'\n"; + break; + } + + ps.print(response); + ps.flush(); + System.out.print("Message sent to server: " + response); + messageCount++; + + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String line = br.readLine(); + System.out.println("Message received from server: " + line + "\n"); + + if (line.contains("Closing connection.")) { + openConnection = false; + socket.close(); + } + } + } + catch(Exception e) + { + System.out.println(e); + System.out.println("Problem with client"); + } + + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpServer.java new file mode 100644 index 0000000000000000000000000000000000000000..d2c7a701f461528ea059c7d9757f31d7faee5526 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework1/YamashitaDeMouraTcpServer.java @@ -0,0 +1,87 @@ +package MV3500Cohort2018JanuaryMarch.homework1; + + +import java.io.*; +import java.net.*; + +/** + * MV3500 + * + * TCP Server. + * This server works with only one client and can exchange + * multiples messages with it. + * + * @author Douglas Yamashita de Moura + * @version 20180212 + * + */ +public class YamashitaDeMouraTcpServer +{ + + public static void main(String[] args) + { + try + { + ServerSocket serverSocket = new ServerSocket(2317); + System.out.print("Server socket created. Waiting for client...\n"); + + Socket clientConnection = serverSocket.accept(); + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))\n"); + + int count = 1; + boolean openConnection = true; + + while(openConnection) + { + String response = ""; + + System.out.println("Request #" + count); + + // Receives message from client + InputStream is = clientConnection.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + String clientMessage = br.readLine(); + System.out.println("The message the client sent was: " + clientMessage + "."); + + // Sends message to client + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + switch (count){ + + case 1: + response = "'I am the server and I accepted the request. Send entity name and position.'\n"; + break; + case 2: + response = "'I confirm the receipt of the message.'\n"; + break; + case 3: + response = "'You are welcome. Closing connection.'\n"; + openConnection = false; + break; + } + + System.out.println("Message sent to client: " + response); + ps.print(response); + ps.flush(); + response = ""; + count++; + + } + clientConnection.close(); + } catch(Exception e){ + System.out.println("Problem with networking"); + System.out.println("Exception: " + e); + } + } + +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelAssignment 2.pptx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelAssignment 2.pptx new file mode 100644 index 0000000000000000000000000000000000000000..65d72be5ab54cca0e078c8da621852bdabbac06b Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelAssignment 2.pptx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..7fdaf94ecca0a3578b9ca3bdda4727bb908288a6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastReceiver.java @@ -0,0 +1,70 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; + +/** + * + * @author mcgredo + */ +public class AngelMulticastReceiver { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + multicastSocket.receive(packet); + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + char type = dis.readChar(); + if (type == 'A') { + float firstNumber = dis.readFloat(); + float secondNumber = dis.readFloat(); + float thirdNumber = dis.readFloat(); + System.out.println("Abrams POS: (x: " + firstNumber + ", y: " + secondNumber +", z: " + thirdNumber + " )"); + } + if (type == 'B') { + int lngth = dis.readInt(); + String informationLine = ""; + for(int i=0; i<lngth; i++) { + informationLine += dis.readChar(); + } + System.out.println(informationLine); + } + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastSenderExample.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastSenderExample.java new file mode 100644 index 0000000000000000000000000000000000000000..bcb08fbe28d9248d8a4e6825353f30a6097ec042 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/AngelMulticastSenderExample.java @@ -0,0 +1,94 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; +import java.util.Random; + +/** + * Looks a lot like a UDP sender. + * + * @author mcgredo + */ +public class AngelMulticastSenderExample { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + Random randomFLT = new Random(); + Random rndFLT = new Random(); + for(int idx = 0; idx < 100; idx++){ + float flt = rndFLT.nextFloat(); + if (flt <=.5){ + dos.writeChars("A"); + dos.writeFloat(randomFLT.nextFloat()*100); + dos.writeFloat(randomFLT.nextFloat()*100); + dos.writeFloat(randomFLT.nextFloat()*100); + } + else if (flt < .8 ) { + dos.writeChars("B"); + dos.writeInt("Information Bravo.".length()); + dos.writeChars("Information Bravo."); + } + else { + dos.writeChars("B"); + dos.writeInt("Information Charlie.".length()); + dos.writeChars("Information Charlie."); + } + byte[] buffer = baos.toByteArray(); + // Put together a packet to send + + // muticast group we are sending to--not a single host + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + + multicastSocket.send(packet); + baos.reset(); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Blankenbeker HW 2 UML.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Blankenbeker HW 2 UML.docx new file mode 100644 index 0000000000000000000000000000000000000000..036c1d1e55e9d95d84fe19e072e033807a1c3a01 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Blankenbeker HW 2 UML.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..d7e9a8945f00a0b9eae2aaa9f842fb657245d5c8 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastReceiver.java @@ -0,0 +1,73 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +/** + * + * @author Michael + */ +public class BlankenbekerMulticastReceiver { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + float firstNumber = dis.readFloat(); + float secondNumber = dis.readFloat(); + float thirdNumber = dis.readFloat(); + + System.out.println("Number received: " + count + " Vehicle position is: (" + firstNumber + ", " + secondNumber+", "+thirdNumber+")"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..c19bf55e3f92ca174c237408a716062436587c0d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerMulticastSender.java @@ -0,0 +1,94 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +/** + * + * @author Michael + */ +public class BlankenbekerMulticastSender { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + BlankenbekerTruck truck = new BlankenbekerTruck(); + while (true) { + truck.move(); + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + float x = truck.getX(); + float y = truck.getY(); + float z = truck.getZ(); + + dos.writeFloat(x); + dos.writeFloat(y); + dos.writeFloat(z); + + byte[] buffer = baos.toByteArray(); + + // Put together a packet to send + + // muticast group we are sending to--not a single host + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + for(int idx = 0; idx < 1; idx++) + { + + multicastSocket.send(packet); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent new multicast packet 1 of 1"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} +} \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerTruck.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerTruck.java new file mode 100644 index 0000000000000000000000000000000000000000..59f0a08ba19334a70651694fb626a5924716d1e6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/BlankenbekerTruck.java @@ -0,0 +1,46 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +//package mv3500code; + +/** + * + * @author Michael + */ +public class BlankenbekerTruck { + private float x; + private float y; + private float z; + + public BlankenbekerTruck(){ + x = 0; + y=0; + z=0; + } + + public void move(){ + x+=1.5; + y+=1.2; + z-=.2; +} + /** + * + * @return + */ + public float getX(){ + return x; + } + + public float getY(){ + return y; + } + + public float getZ(){ + return z; + } +} + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..e02345c08f84d0be8d352c90be4dc2e019b34f06 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastReceiver.java @@ -0,0 +1,67 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.net.UnknownHostException; +/** + * + * @author emilyconard + */ +public class ConardMulticastReceiver { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + float firstNumber = dis.readInt(); + float secondNumber = dis.readInt(); + float thirdNumber = dis.readInt(); + + System.out.println("Number received: " + count + " ID: " + firstNumber + " xcord: " + secondNumber + " ycord: "+ thirdNumber); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..108b25449ed8af73af3ed61fe47b51f7f6eb839b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/ConardMulticastSender.java @@ -0,0 +1,69 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.MulticastSocket; + + +/** + * + * @author emilyconard + */ +public class ConardMulticastSender { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + int ID = 27; + int xcord = 5; + int ycord = 7; + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(ID); + dos.writeInt(xcord); + dos.writeInt(ycord); + byte[] buffer = baos.toByteArray(); + + + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + for(int idx = 0; idx < 100; idx++) + { + multicastSocket.send(packet); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWreceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWreceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..ad417acfd360b933532a3870ee9c5e3af001c22d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWreceiver.java @@ -0,0 +1,65 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/** + * This assignment uses the code from MV3500 example "multicastExample1" + * modifications were made to way the packet is read to facilitate the double + * instead of the float. + * + * @author Brian + */ +import java.io.*; +import java.net.*; + + +public class HanleyMulticastHWreceiver { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + double firstNumber = dis.readDouble(); + double secondNumber = dis.readDouble(); + + System.out.println("Number received: " + count + " X Pos: " + firstNumber + " Y Pos: " + secondNumber); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWsender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWsender.java new file mode 100644 index 0000000000000000000000000000000000000000..fbd8b1b3bc3f11a9de90f03d18a83fe51b49ada5 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyMulticastHWsender.java @@ -0,0 +1,87 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/** + * This assignment uses the code from MV3500 example "multicastExample1" + * modifications were made to the packet creation and where the packet is + * assembled. + * + * @author Brian + */ + + +import java.io.*; +import java.net.*; + + +public class HanleyMulticastHWsender { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + private int velocity; + private float xPos; + private float yPos; + + + public static void main(String[] args) + { + int velocity = 2; + int dir = 45; + double xPos = 0; + double yPos = 2; + + + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + for(int idx = 0; idx < 100; idx++) + { + + xPos = xPos + (Math.cos(Math.toRadians(dir))*velocity); //computes the horixontal displacement for each movement based on velocity - this is a fixed velocity and time increment + yPos = yPos + (Math.sin(Math.toRadians(dir))*velocity); //computes the vertical displacement for each movement based on velocity - this is a fixed velocity and time increment + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeDouble(xPos); + dos.writeDouble(yPos); + + + byte[] buffer = baos.toByteArray(); + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + multicastSocket.send(packet); + baos.reset(); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyREADMEMulticastHW.txt b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyREADMEMulticastHW.txt new file mode 100644 index 0000000000000000000000000000000000000000..f5daac6fdb9e8c2c8f6babbcbae55471257db9df --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyREADMEMulticastHW.txt @@ -0,0 +1,35 @@ +Hanley README for Multicast Homework + +Modified the code from multicast example 1. + +- adjusted packet to get compiled for every send +- computed the "position" of the entity for each packet +- shout out to Chris A for identifying the need to change the receiver to listen for doubles and not floats + + +********** System outputs for classes: + +Sender: +run-single: +/239.1.2.15 +Sent multicast packet 0 of 100 +Sent multicast packet 1 of 100 +Sent multicast packet 2 of 100 +Sent multicast packet 3 of 100 +Sent multicast packet 4 of 100 +Sent multicast packet 5 of 100 +Sent multicast packet 6 of 100 +Sent multicast packet 7 of 100 + + +Receiver: +run-single: +/239.1.2.15 +Number received: 1 X Pos: 1.4142135623730951 Y Pos: 3.414213562373095 +Number received: 2 X Pos: 2.8284271247461903 Y Pos: 4.82842712474619 +Number received: 3 X Pos: 4.242640687119286 Y Pos: 6.242640687119285 +Number received: 4 X Pos: 5.656854249492381 Y Pos: 7.65685424949238 +Number received: 5 X Pos: 7.0710678118654755 Y Pos: 9.071067811865476 +Number received: 6 X Pos: 8.485281374238571 Y Pos: 10.485281374238571 +Number received: 7 X Pos: 9.899494936611667 Y Pos: 11.899494936611667 +Number received: 8 X Pos: 11.313708498984763 Y Pos: 13.313708498984763 \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyUMLDrawingHW2.vsdx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyUMLDrawingHW2.vsdx new file mode 100644 index 0000000000000000000000000000000000000000..ab061d5c900f679a0fa02e97feb5a04121dff994 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/HanleyUMLDrawingHW2.vsdx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastAssignment02.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastAssignment02.pdf new file mode 100644 index 0000000000000000000000000000000000000000..cab970afac859e2b3c62e14db7b0f008624cff03 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastAssignment02.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..831bb617721d791133d4c8efea06be038fae96f2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver.java @@ -0,0 +1,46 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.net.UnknownHostException; + +/** + * + * @author Rico + */ +public class LandasMulticastReceiver { + + final static String INET_ADDR = "239.1.2.15"; + final static int PORT = 1717; + + public static void main(String[] args) throws UnknownHostException { + // address that we are connecting to + InetAddress address = InetAddress.getByName(INET_ADDR); + + // buffer of bytes + // the incoming bytes containing the information from the server + // ** this stored the excess array slot and printed extra + //byte[] buf = new byte[256]; + + // Multicast socket + try (MulticastSocket clientSocket = new MulticastSocket(PORT)){ + // Join + clientSocket.joinGroup(address); + + while (true) { + byte[] buf = new byte[256]; + // Receive information and print + DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); + clientSocket.receive(msgPacket); + + String msg = new String(buf, 0, buf.length); + System.out.println("Socket 1 received msg: " + msg); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver2.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver2.java new file mode 100644 index 0000000000000000000000000000000000000000..96c2c15178fdeb980ca311a8b79c620e859b5a12 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastReceiver2.java @@ -0,0 +1,46 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; +import java.net.UnknownHostException; + +/** + * + * @author Rico + */ +public class LandasMulticastReceiver2 { + + final static String INET_ADDR = "239.1.2.15"; + final static int PORT = 1717; + + public static void main(String[] args) throws UnknownHostException { + // address that we are connecting to + InetAddress address = InetAddress.getByName(INET_ADDR); + + // buffer of bytes, which will be used to store + // the incoming bytes containing the information from the server + // ** this stored the excess array slot and printed extra + //byte[] buf = new byte[256]; + + // Multicast socket + try (MulticastSocket clientSocket = new MulticastSocket(PORT)){ + // Join + clientSocket.joinGroup(address); + + while (true) { + byte[] buf = new byte[256]; + // Receive information and print + DatagramPacket msgPacket = new DatagramPacket(buf, buf.length); + clientSocket.receive(msgPacket); + + String msg = new String(buf, 0, buf.length); + System.out.println("Socket 2 received msg: " + msg); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..8bbcd839df39b1a49bb7d801a31ed93d75762785 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender.java @@ -0,0 +1,42 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +/** + * + * @author Rico + */ +public class LandasMulticastSender { + + final static String INET_ADDR = "239.1.2.15"; + final static int PORT = 1717; + + public static void main(String[] args) throws UnknownHostException, InterruptedException { + // address that we are connecting to + InetAddress addr = InetAddress.getByName(INET_ADDR); + + // new DatagramSocket + // used to send the data + try (DatagramSocket serverSocket = new DatagramSocket()) { + for (int i = 0; i < 100; i++) { + String msg = "Server 1 sent message no " + i; + + // packet + // (in the form of bytes) + DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(), + msg.getBytes().length, addr, PORT); + serverSocket.send(msgPacket); + + System.out.println("Server 1 sent packet with msg: " + msg); + Thread.sleep(1000); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender2.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender2.java new file mode 100644 index 0000000000000000000000000000000000000000..c28b2780bc32ce617ede330fffc9bfaf25ba1ff4 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasMulticastSender2.java @@ -0,0 +1,42 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.IOException; +import java.net.DatagramPacket; +import java.net.DatagramSocket; +import java.net.InetAddress; +import java.net.UnknownHostException; + +/** + * + * @author Rico + */ +public class LandasMulticastSender2 { + + final static String INET_ADDR = "239.1.2.15"; + final static int PORT = 1717; + + public static void main(String[] args) throws UnknownHostException, InterruptedException { + // address that we are connecting to + InetAddress addr = InetAddress.getByName(INET_ADDR); + + // new DatagramSocket + // used to send the data + try (DatagramSocket serverSocket = new DatagramSocket()) { + for (int j = 0; j < 100; j++) { + String msg = "Server 2 sent message no " + j; + + // packet + // (in the form of bytes) + DatagramPacket msgPacket = new DatagramPacket(msg.getBytes(), + msg.getBytes().length, addr, PORT); + serverSocket.send(msgPacket); + + System.out.println("Server 2 sent packet with msg: " + msg); + Thread.sleep(1000); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasUMLAssignment02_2_2.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasUMLAssignment02_2_2.pdf new file mode 100644 index 0000000000000000000000000000000000000000..300376e40266aaefa33d17b619d4bdfb10dd513c Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/LandasUMLAssignment02_2_2.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..2ffaee524ec5af5ff30830661253e35f804bbe05 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastReceiver.java @@ -0,0 +1,98 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; +import javax.swing.*; +import java.awt.*; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; + + +/** + * + * @author mcgredo + */ +public class MaroonMulticastReceiver { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + JFrame guiFrame = new JFrame(); + guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + guiFrame.setTitle("Read a message"); + guiFrame.setSize(300,250); + guiFrame.setLocationRelativeTo(null); + + final JPanel output = new JPanel(); + output.setVisible(true); + JLabel outputLbl= new JLabel("Hit the Button"); + output.add(outputLbl); + + JButton MCButton = new JButton( "Push Me"); + + MCButton.addActionListener(new ActionListener(){ + @Override + public void actionPerformed(ActionEvent event){ + try { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + int firstNumber = dis.readInt(); + int messageLength = dis.readInt(); + String message = ""; + for (int i = 0; i < messageLength; i++){ + message += dis.readChar(); + } + + + outputLbl.setText(message); + + System.out.println("Number received: " + count + " First number:" + firstNumber + " message:" + message); + } + catch(Exception e){ + System.out.println(e); + } + } + } + ); + + + guiFrame.add(output, BorderLayout.CENTER); + guiFrame.add(MCButton,BorderLayout.NORTH); + guiFrame.setVisible(true); + + + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastSenderExample.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastSenderExample.java new file mode 100644 index 0000000000000000000000000000000000000000..e263b5750c6caacb12d85fcf45bfb40c6ce1658e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/MaroonMulticastSenderExample.java @@ -0,0 +1,88 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; + +/** + * Looks a lot like a UDP sender. + * + * @author mcgredo + */ +public class MaroonMulticastSenderExample { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; // Time to Live is decrement counter to limit scope + + public static void main(String[] args) + { + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(1); + String message = "**********************************"; + dos.writeInt(message.length()); + dos.writeChars(message); + byte[] buffer = baos.toByteArray(); + + DatagramPacket packet1 = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + baos.reset(); + dos.writeInt(2); + message = "<===========================>"; + + dos.writeInt(message.length()); + dos.writeChars(message); + buffer = baos.toByteArray(); + + DatagramPacket packet2 = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + for(int idx = 0; idx < 1000; idx++) + { + + multicastSocket.send(packet1); + multicastSocket.send(packet2); + + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/README.txt b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/README.txt new file mode 100644 index 0000000000000000000000000000000000000000..49171e5b8742247fdff794ea25a3a222f29ae887 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/README.txt @@ -0,0 +1,6 @@ +README files for your project (such as SmithREADME.txt or SmithREADME.md) help +document what works, references of interest, what problems were encountered, +and what TODO items remain. + +This documentation not only helps others, but also helps you keep track of +progress for ongoing or future improvements. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Sasala UML Diagram & Screen Shot (HW2).docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Sasala UML Diagram & Screen Shot (HW2).docx new file mode 100644 index 0000000000000000000000000000000000000000..211194bbc15369dccefa6c4c12c1173c55f91352 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/Sasala UML Diagram & Screen Shot (HW2).docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..ff2e874ab5a1655b9ac057d436a6e11bbac027a7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastReceiver.java @@ -0,0 +1,62 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; + +/** + * + * @author mcgredo + */ +public class SasalaMulticastReceiver { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + float temperature = dis.readFloat(); + String DTG = dis.readLine(); + + System.out.println("Time: " + DTG + " Temperature:" + temperature); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..fdafb40edd73b59203f4c446e2f21454aa5fbca6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SasalaMulticastSender.java @@ -0,0 +1,76 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + + + +import java.io.*; +import java.net.*; +import java.time.LocalDateTime; + +/** + * Looks a lot like a UDP sender. + * + * @author mcgredo + */ +public class SasalaMulticastSender { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + + for(int idx = 0; idx < 100; idx++) + { + double temperature = 100 * Math.random(); + LocalDateTime LDT = LocalDateTime.now(); + String time = LDT.toString(); + + dos.writeFloat((float) temperature); + dos.writeChars(time); + + // Put together a packet to send + // muticast group we are sending to--not a single host + byte[] buffer = baos.toByteArray(); + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + multicastSocket.send(packet); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + + baos.reset(); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellConsole.JPG b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellConsole.JPG new file mode 100644 index 0000000000000000000000000000000000000000..880688e3de41e3dd8e3fdd31b65837686a8d8c8c Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellConsole.JPG differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastClient.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastClient.java new file mode 100644 index 0000000000000000000000000000000000000000..83f965569b9974cd0761c46da779294dd8437610 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastClient.java @@ -0,0 +1,71 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +//package HW2; + +import java.io.ByteArrayInputStream; +import java.io.DataInputStream; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +/** + * + * @author Justin Snell + */ +public class SnellMulticastClient { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + int firstNumber = dis.readInt(); + int secondNumber = dis.readInt(); + + System.out.println("Number received: " + count + " xpos:" + firstNumber + " ypos:" + secondNumber); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastServer.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastServer.java new file mode 100644 index 0000000000000000000000000000000000000000..5b92d0f7024a0da863b7cded38433ac184f3dd00 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/SnellMulticastServer.java @@ -0,0 +1,73 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +//package HW2; + +import java.io.ByteArrayOutputStream; +import java.io.DataOutputStream; +import java.net.DatagramPacket; +import java.net.InetAddress; +import java.net.MulticastSocket; + +public class SnellMulticastServer { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int xpos = 12; + int ypos = 15; + + // Put together a message with binary content. "ByteArrayOutputStream" + // is a java.io utility that lets us put together an array of binary + // data, which we put into the UDP packet. + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeInt(xpos); + dos.writeInt(ypos); + byte[] buffer = baos.toByteArray(); + + // Put together a packet to send + // muticast group we are sending to--not a single host + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + for(int idx = 0; idx < 100; idx++) + { + multicastSocket.send(packet); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMultiCastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMultiCastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..79ea1e5fbf4c4b8dc7f0572ad24a0d90849bb63b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMultiCastReceiver.java @@ -0,0 +1,65 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/** + * This assignment uses the code from MV3500 example "multicastExample1" + * modifications were made to way the packet is read to facilitate the double + * instead of the float. + * + * @author codyt + */ +import java.io.*; +import java.net.*; + + +public class TackettMultiCastReceiver { + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + int count = 0; + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + + multicastSocket.receive(packet); + count++; + + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + double firstNumber = dis.readDouble(); + double secondNumber = dis.readDouble(); + + System.out.println("Number received: " + count + " X Pos: " + firstNumber + " Y Pos: " + secondNumber); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..98e89d497eb4ff36d5a11b51ceb3df3c5cd6ba54 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/TackettMulticastSender.java @@ -0,0 +1,87 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +/** + * This assignment uses the code from MV3500 example "multicastExample1" + * modifications were made to the packet creation and where the packet is + * assembled. + * + * @author Brian + */ + + +import java.io.*; +import java.net.*; + + +public class TackettMulticastSender { + public static final String MULTICAST_ADDRESS = "172.20.144.145"; + public static final int DESTINATION_PORT = 1717; + /** How many routers can be crossed */ + public static final int TTL = 10; + private int velocity; + private float xPos; + private float yPos; + + + public static void main(String[] args) + { + int velocity = 3; + int direction = 180; + double xPos = 0; + double yPos = 2; + + + try + { + // This is a java/IPv6 problem. You should also add it to the + // arguments used to start the app, eg -Djava.net.preferIPv4Stack=true + // set in the "run" section of preferences. Also, typically + // netbeans must be restarted after these settings. + // https://stackoverflow.com/questions/18747134/getting-cant-assign-requested-address-java-net-socketexception-using-ehcache + System.setProperty("java.net.preferIPv4Stack", "true"); + + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + // Join group useful on receiving side + multicastSocket.joinGroup(multicastAddress); + // You can join multiple groups here + + + // How fast does this go? Does UDP try to slow it down, or does + // this cause network problems? (hint: yes for an unlimited send + // rate, unlike TCP). How do you know on the receiving side + // that you haven't received a duplicate UDP packet, out of + // order packet, or dropped packet? + + for(int idx = 0; idx < 100; idx++) + { + + xPos = xPos + (Math.cos(Math.toRadians(direction))*velocity); //computes the horixontal displacement for each movement based on velocity - this is a fixed velocity and time increment + yPos = yPos + (Math.sin(Math.toRadians(direction))*velocity); //computes the vertical displacement for each movement based on velocity - this is a fixed velocity and time increment + + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + dos.writeDouble(xPos); + dos.writeDouble(yPos); + + + byte[] buffer = baos.toByteArray(); + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + + multicastSocket.send(packet); + baos.reset(); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraAssignment2.docx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraAssignment2.docx new file mode 100644 index 0000000000000000000000000000000000000000..957bf719eb838584792896d4d449431f122dd497 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraAssignment2.docx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraEntity.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..c5665e9c7d5aef01eb547cb40ebb864a9695c79a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraEntity.java @@ -0,0 +1,102 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +//package homework2; + +/** + * MV3500 + * + * Entity + * + * @author Douglas Yamashita de Moura + * @version 20180227 + * + */ +public class YamashitaDeMouraEntity { + + private String name; + private float x; + private float y; + private float z; + private float speed; + + public YamashitaDeMouraEntity (String name, float x, float y, float z, float speed) { + this.name = name; + this.x = x; + this.y = y; + this.z = z; + this.speed = speed; + } + + /** + * @return the x + */ + public float getX() { + return x; + } + + /** + * @param x the x to set + */ + public void setX(float x) { + this.x = x; + } + + /** + * @return the y + */ + public float getY() { + return y; + } + + /** + * @param y the y to set + */ + public void setY(float y) { + this.y = y; + } + + /** + * @return the z + */ + public float getZ() { + return z; + } + + /** + * @param z the z to set + */ + public void setZ(float z) { + this.z = z; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the velocity + */ + public float getVelocity() { + return speed; + } + + /** + * @param velocity the velocity to set + */ + public void setVelocity(float velocity) { + this.speed = velocity; + } + + + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastEntity.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastEntity.java new file mode 100644 index 0000000000000000000000000000000000000000..7165916966a6d81a77fcdc3892a1d948c0493737 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastEntity.java @@ -0,0 +1,102 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + +//package homework2; + +/** + * MV3500 + * + * Entity + * + * @author Douglas Yamashita de Moura + * @version 20180227 + * + */ +public class YamashitaDeMouraMulticastEntity { + + private String name; + private float x; + private float y; + private float z; + private float speed; + + public YamashitaDeMouraMulticastEntity (String name, float x, float y, float z, float speed) { + this.name = name; + this.x = x; + this.y = y; + this.z = z; + this.speed = speed; + } + + /** + * @return the x + */ + public float getX() { + return x; + } + + /** + * @param x the x to set + */ + public void setX(float x) { + this.x = x; + } + + /** + * @return the y + */ + public float getY() { + return y; + } + + /** + * @param y the y to set + */ + public void setY(float y) { + this.y = y; + } + + /** + * @return the z + */ + public float getZ() { + return z; + } + + /** + * @param z the z to set + */ + public void setZ(float z) { + this.z = z; + } + + /** + * @return the name + */ + public String getName() { + return name; + } + + /** + * @param name the name to set + */ + public void setName(String name) { + this.name = name; + } + + /** + * @return the velocity + */ + public float getVelocity() { + return speed; + } + + /** + * @param velocity the velocity to set + */ + public void setVelocity(float velocity) { + this.speed = velocity; + } + + + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..071fd2d9383c9dcf27dff2235550ef6a217ba9d7 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastReceiver.java @@ -0,0 +1,79 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.*; +import java.net.*; +import java.util.Random; + +/** + * MV3500 + * + * Multicast Receiver + * + * @author Douglas Yamashita de Moura + * @version 20180227 + * + */ +public class YamashitaDeMouraMulticastReceiver { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + public static final int TTL = 10; + + public static void main(String[] args) + { + try + { + System.setProperty("java.net.preferIPv4Stack", "true"); + MulticastSocket multicastSocket = new MulticastSocket(DESTINATION_PORT); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + multicastSocket.joinGroup(multicastAddress); + int count = 0; + + int randomReceiver = new Random().nextInt(100); + System.out.println("=== MULTICAST RECEIVER " + randomReceiver + " ==="); + + while(true) + { + byte[] packetArray = new byte[1500]; + DatagramPacket packet = new DatagramPacket(packetArray, packetArray.length); + multicastSocket.receive(packet); + count++; + ByteArrayInputStream bais = new ByteArrayInputStream(packet.getData()); + DataInputStream dis = new DataInputStream(bais); + char entity = dis.readChar(); + String name = ""; + int nameLength = 0; + switch(entity) { + case 'A': + nameLength = 4; + name = "A"; + break; + case 'B': + nameLength = 4; + name = "B"; + break; + } + + // Read name + for (int i = 0; i < nameLength; i++) { + name += dis.readChar(); + } + + // Read Position + float xPos = dis.readFloat(); + float yPos = dis.readFloat(); + float zPos = dis.readFloat(); + System.out.println("Entity '" + name + "' with position (" + xPos + + ", " + yPos + ", " + zPos +")."); + System.out.println("Number received: " + count); + } + } + catch(Exception e) + { + System.out.println(e); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastSender.java new file mode 100644 index 0000000000000000000000000000000000000000..f61601a21da2ac2649bd5bae43703881abfc1e1f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraMulticastSender.java @@ -0,0 +1,87 @@ +package MV3500Cohort2018JanuaryMarch.homework2; + + +import java.io.*; +import java.net.*; +import java.util.Random; + +/** + * MV3500 + * + * Multicast Sender + * + * @author Douglas Yamashita de Moura + * @version 20180227 + * + */ +public class YamashitaDeMouraMulticastSender { + + public static final String MULTICAST_ADDRESS = "239.1.2.15"; + public static final int DESTINATION_PORT = 1717; + public static final int TTL = 10; + + + public static void main(String[] args) + { + YamashitaDeMouraMulticastEntity entityA = new YamashitaDeMouraMulticastEntity("Alpha", 0, 0, 0, 2); + YamashitaDeMouraMulticastEntity entityB = new YamashitaDeMouraMulticastEntity("Bravo", 0, 0, 0, 3); + + try + { + System.setProperty("java.net.preferIPv4Stack", "true"); + + MulticastSocket multicastSocket = new MulticastSocket(1718); + multicastSocket.setTimeToLive(TTL); + InetAddress multicastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + System.out.println(multicastAddress); + multicastSocket.joinGroup(multicastAddress); + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + + Random randomProb = new Random(); + + System.out.println("=== MULTICAST SENDER ==="); + + for(int idx = 1; idx < 100; idx++) + { + int prob = randomProb.nextInt(5); + + if(prob < 2) { + dos.writeChars(entityA.getName()); + // Move only in x direction + float newPos = entityA.getX()+entityA.getVelocity(); + entityA.setX(newPos); + dos.writeFloat(entityA.getX()); + dos.writeFloat(entityA.getY()); + dos.writeFloat(entityA.getZ()); + System.out.println("Entity '" + entityA.getName() + + "' with position (" + entityA.getX() + ", " + + entityA.getY() + ", " + entityA.getZ() + ")"); + } else if (prob < 5) { + dos.writeChars(entityB.getName()); + dos.writeFloat(entityB.getX()); + // Move only in y direction + float newPos = entityB.getY()+entityB.getVelocity(); + entityB.setY(newPos); + dos.writeFloat(entityB.getY()); + dos.writeFloat(entityB.getZ()); + System.out.println("Entity '" + entityB.getName() + + "' with position (" + entityB.getX() + ", " + + entityB.getY() + ", " + entityB.getZ() + ")"); + } + + byte[] buffer = baos.toByteArray(); + + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, multicastAddress, DESTINATION_PORT); + multicastSocket.send(packet); + baos.reset(); + Thread.sleep(1000); // Send 100, one per second + System.out.println("Sent multicast packet " + idx + " of 100"); + } + } + catch(Exception e) + { + System.out.println(e); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraOutput.jpg b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraOutput.jpg new file mode 100644 index 0000000000000000000000000000000000000000..ea97fa9be246b0dadc110583cbd7032f1bac3886 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework2/YamashitaDeMouraOutput.jpg differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..dadc2eb28d35432885fda9c774aebbec215c8616 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angel_OpenDisEspduSender.java @@ -0,0 +1,343 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +//package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Angel_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)2); // AIR (vs air, surface, subsurface, space) + entityType.setCategory((short)2); // Fighter/Attack + entityType.setSubcategory((short)2); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + double disCoordinates1[] = CoordinateConversions.getXYZfromLatLonDegrees(36.593731, -121.882534, 1.0); + double disCoordinates2[] = CoordinateConversions.getXYZfromLatLonDegrees(36.594548, -121.882651, 1.0); + double disCoordinates3[] = CoordinateConversions.getXYZfromLatLonDegrees(36.596826, -121.882694, 1.0); + double disCoordinates4[] = CoordinateConversions.getXYZfromLatLonDegrees(36.598394, -121.883188, 1.0); + double disCoordinates5[] = CoordinateConversions.getXYZfromLatLonDegrees(36.599927, -121.883510, 1.0); + double disCoordinates6[] = CoordinateConversions.getXYZfromLatLonDegrees(36.599979, -121.887286, 1.0); + double disCoordinates7[] = CoordinateConversions.getXYZfromLatLonDegrees(36.598170, -121.887715, 1.0); + double disCoordinates8[] = CoordinateConversions.getXYZfromLatLonDegrees(36.596826, -121.888895, 1.0); + double disCoordinates9[] = CoordinateConversions.getXYZfromLatLonDegrees(36.595121, -121.889239, 1.0); + double disCoordinates10[] = CoordinateConversions.getXYZfromLatLonDegrees(36.594415,-121.885934, 1.0); + + double[][] disCoords = {disCoordinates1, disCoordinates2, disCoordinates3, disCoordinates4, + disCoordinates5, disCoordinates6, disCoordinates7, disCoordinates8, disCoordinates8, + disCoordinates10}; + + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + + //double direction = Math.pow((double)(-1.0), (double)(idx)); + //lon = lon + (direction * 0.00006); + //System.out.println(lon); + + + + Vector3Double location = espdu.getEntityLocation(); + int res = idx/2 % 10; + location.setX(disCoords[res][0]); + location.setY(disCoords[res][1]); + location.setZ(disCoords[res][2]); + //System.out.println("lat, lon:" + lat + ", " + lon); + //System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + + //FirePdu fire = new FirePdu(); + //byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/AngelopoulosREADME.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/AngelopoulosREADME.md new file mode 100644 index 0000000000000000000000000000000000000000..bf6e056dcfd35700eaedff6ff73b6c0b6e43d41a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/AngelopoulosREADME.md @@ -0,0 +1,34 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + +The armor (Enhanced Ground Combat Vehicle) travels from intersection of Freemont and 68, down Camino Aguajito, +left on Del Monte Ave, Left on Camino El Estero, and finally a left on Fremont to the beginning. The travel movement is +roughly 1/3 of a mile every 24 seconds. It might be a bit fast....but its ARMY/MARINE Strong! + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + +Some examples of PDUs within WireShark + +111 32.870689 172.20.144.243 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Air, (1:1:2) +110 32.870603 172.20.144.243 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Air, (1:1:2) +97 29.761150 172.20.144.243 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Air, (1:1:2) + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..75f5caf1ddc7fed9a2c5ac6d83bc52d1e4fa1337 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..159aa2e788491aa6a444ff345031cbd29ecc337c Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Angelopoulos_dispackets.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin new file mode 100644 index 0000000000000000000000000000000000000000..8dc1bd8f7790381bfa99bfd65342bf48ee6e65dd Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..5ed6ff1e1123af2dd04e7e9c8247aa60ad6c0f66 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerDISpacketsHW3.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerHW3README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerHW3README.md new file mode 100644 index 0000000000000000000000000000000000000000..c77377b79cd3818957b32fab44892fd2da0f1ec0 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerHW3README.md @@ -0,0 +1,30 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [X] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + + The track consists of a highway driving route from Monterey, CA to Palmdale, CA. + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + + Wireshark output depicted activity when PDUs were being created. + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... + +PDU file succesfully recorded and played back using the X3D-Edit tools. diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..0f4df60175caaad8b3dbbe3306a4862b21af96e6 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/BlankenbekerOpenDisEspduSender.java @@ -0,0 +1,366 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class BlankenbekerOpenDisEspduSender +{ + + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + private static final ArrayList <Float[]> track = new ArrayList<>(); + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + //double lat = 36.595517; + //double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.MULTICAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.59135f; + TrackCoor1[1] = -121.88051f; + track.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.59487f; + TrackCoor2[1] = -121.86739f; + track.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.63259f; + TrackCoor3[1] = -121.66926f; + track.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.64481f; + TrackCoor4[1] = -121.61162f; + track.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 35.64239f; + TrackCoor5[1] = -120.68503f; + track.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 35.61577f; + TrackCoor6[1] = -119.65283f; + track.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 34.76589f; + TrackCoor7[1] = -118.79854f; + track.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 34.77651f; + TrackCoor8[1] = -118.17049f; + track.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 34.5806f; + TrackCoor9[1] = -118.1334f; + track.add(TrackCoor9); + +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + Float lat = track.get(idx)[0]; + Float lon = track.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon:" + lat + ", " + lon); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..ea9072fa9d66b2ed6404632c7260c6ec19fe92da --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellOpenDisEspduSender.java @@ -0,0 +1,326 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class ConardSnellOpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + +// double direction = Math.pow((double)(-1.0), (double)(idx)); + lon = Math.cos(idx)*20; + lat = Math.sin(idx)*20; +// lon = lon + (direction * 0.00006); +// System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon:" + lat + ", " + lon); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellREADME.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellREADME.md new file mode 100644 index 0000000000000000000000000000000000000000..e8ed374f19f418ece8b55675e3738cf042ecf265 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnellREADME.md @@ -0,0 +1,24 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnelldispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnelldispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..4659ec9fc4630f41171421cb6370a8e141530720 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/ConardSnelldispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/EspduReceiver.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/EspduReceiver.java new file mode 100644 index 0000000000000000000000000000000000000000..e89962394439353c540652c529be2f580721bc13 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/EspduReceiver.java @@ -0,0 +1,73 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +import java.net.*; +import java.util.*; + +import edu.nps.moves.disutil.*; + +import edu.nps.moves.dis.*; + +/** + * Receives PDUs from the network in IEEE format. + * + * @author DMcG + * @version $Id:$ + */ +public class EspduReceiver { + + /** Max size of a PDU in binary format that we can receive. This is actually + * somewhat outdated--PDUs can be larger--but this is a reasonable starting point + */ + public static final int MAX_PDU_SIZE = 8192; + + public static void main(String args[]) { + MulticastSocket socket; + DatagramPacket packet; + InetAddress address; + PduFactory pduFactory = new PduFactory(); + + try { + // Specify the socket to receive data + socket = new MulticastSocket(3001); + socket.setBroadcast(true); + + //address = InetAddress.getByName(EspduSender.DEFAULT_MULTICAST_GROUP); + //socket.joinGroup(address); + + // Loop infinitely, receiving datagrams + while (true) { + byte buffer[] = new byte[MAX_PDU_SIZE]; + packet = new DatagramPacket(buffer, buffer.length); + + socket.receive(packet); + + List<Pdu> pduBundle = pduFactory.getPdusFromBundle(packet.getData()); + System.out.println("Bundle size is " + pduBundle.size()); + + Iterator it = pduBundle.iterator(); + + while(it.hasNext()) + { + Pdu aPdu = (Pdu)it.next(); + + System.out.print("got PDU of type: " + aPdu.getClass().getName()); + if(aPdu instanceof EntityStatePdu) + { + EntityID eid = ((EntityStatePdu)aPdu).getEntityID(); + Vector3Double position = ((EntityStatePdu)aPdu).getEntityLocation(); + System.out.print(" EID:[" + eid.getSite() + ", " + eid.getApplication() + ", " + eid.getEntity() + "] "); + System.out.print(" Location in DIS coordinates: [" + position.getX() + ", " + position.getY() + ", " + position.getZ() + "]"); + } + System.out.println(); + } // end trop through PDU bundle + + } // end while + } // End try + catch (Exception e) { + + System.out.println(e); + } + + + } // end main +} // end class diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/HanleyREADME.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/HanleyREADME.md new file mode 100644 index 0000000000000000000000000000000000000000..9d3784a7dc2868d5a97581bfd594512ab3f1f79e --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/HanleyREADME.md @@ -0,0 +1,518 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [X] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... + + + +Track of Interest +- track will be a M1A1 mine roller tank + +Modify your example file to produce track PDUs (and be cool) + modified direction of travel by adding latitude displacement. Tried to add + an angular velocity, but could not get it to work + + +Wireshark output: +920 178.601803 172.20.152.80 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) +942 181.792430 172.20.152.80 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) + + +Output from runningHanley_OpnDisEspduSender +ant -f C:\\Users\\Brian\\Documents\\NetBeansProjects\\NetworkedGraphicsMV3500(try2)\\NetworkedGraphicsMV3500\\projects\\Assignments -Djavac.includes=Hanley_OpenDisEspduSender.java -Dnb.internal.action.name=run.single -Drun.class=Hanley_OpenDisEspduSender run-single +init: +Deleting: C:\Users\Brian\Documents\NetBeansProjects\NetworkedGraphicsMV3500(try2)\NetworkedGraphicsMV3500\projects\Assignments\build\built-jar.properties +deps-jar: +Updating property file: C:\Users\Brian\Documents\NetBeansProjects\NetworkedGraphicsMV3500(try2)\NetworkedGraphicsMV3500\projects\Assignments\build\built-jar.properties +Compiling 1 source file to C:\Users\Brian\Documents\NetBeansProjects\NetworkedGraphicsMV3500(try2)\NetworkedGraphicsMV3500\projects\Assignments\build\classes +compile-single: +run-single: +Sending 5000 ESPDU packets to /239.1.2.3 +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #0 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #1 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #2 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #3 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #4 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #5 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #6 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #7 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #8 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #9 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #10 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #11 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #12 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #13 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #14 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #15 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #16 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #17 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #18 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #19 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #20 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #21 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #22 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #23 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #24 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #25 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #26 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #27 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #28 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #29 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #30 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #31 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #32 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #33 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #34 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #35 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #36 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #37 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #38 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #39 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #40 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #41 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #42 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #43 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #44 EID=[1,1,2] + DIS coordinates location=[-2707484.0531117637,-4353663.186028796,3781457.4477844355] + Location (lat/lon/alt): [36.595597, -121.87692000000001, 0.9999999990686774] +-121.877 +lat, lon:36.595517, -121.877 +DIS coord:-2707492.9269245286, -4353663.899966802, 3781450.3202754413 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +Espdu #45 EID=[1,1,2] + DIS coordinates location=[-2707492.9269245286,-4353663.899966802,3781450.3202754413] + Location (lat/lon/alt): [36.59551700000001, -121.877, 0.9999999990686774] +-121.87692 +lat, lon:36.595597, -121.87692 +DIS coord:-2707484.0531117637, -4353663.186028796, 3781457.4477844355 +Sending broadcast datagram packet to /127.255.255.255 +Sending broadcast datagram packet to /192.168.112.255 +Sending broadcast datagram packet to /192.168.111.255 +Sending broadcast datagram packet to /172.20.159.255 +BUILD STOPPED (total time: 2 minutes 29 seconds) diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..e987af041e03a6a1f3827677662032e831e5ee2d --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_OpenDisEspduSender.java @@ -0,0 +1,325 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Hanley_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(224); // UK + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)4); // M1A1 w/ mine roller + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + double direction = Math.pow((double)(-1.0), (double)(idx)); + lon = lon + (direction * 0.00008); + lat = lat + (direction * 0.00008); + System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon:" + lat + ", " + lon); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + //FirePdu fire = new FirePdu(); + //byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + //packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + // socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); + System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..2d9540183675a889d507c4cffd72d88b0bd8192f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..93134b8f5e18fbed158dc694f3d816c7537097a7 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Hanley_dispackets.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/LandasREADME.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/LandasREADME.md new file mode 100644 index 0000000000000000000000000000000000000000..4f4db0c3aec7ea13bd39745381107b1fd36d8e86 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/LandasREADME.md @@ -0,0 +1,41 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... + + + +Track of interest (my route to school): +36.585657, -121.879920 +36.584853, -121.880024 +36.583500, -121.879615 +36.586307, -121.874582 +36.588670, -121.877928 +36.591124, -121.880074 +36.592827, -121.877149 +36.594051, -121.877452 +36.594245, -121.876477 +36.595230, -121.877537 + + + diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..d542f4b554d4d03eabeeb2e13be49b45c1ead69b Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..d033f7d48d0eaf5a23c8dda64764b172e742ba24 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_Assignment3_dispackets.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..65be939cb70cb9f6476bab76076ab8d968dde46a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.java @@ -0,0 +1,387 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Landas_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + + private static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office +// double lat = 36.595517; +// double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)20); // Maintenance equipment trailer(20) + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + +// Point point = new Point(); +// point.setX(1.5f); +// point.setY(1.9f); +// +// List<Point> track_coordinates = new ArrayList<Point>(); +// track_coordinates.add(point); +// System.out.println("********" + track_coordinates); + +// ArrayList <Float[]> track_coordinates = new ArrayList<>(); + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.585657f; + TrackCoor1[1] = -121.879920f; + track_coordinates.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.584853f; + TrackCoor2[1] = -121.880024f; + track_coordinates.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.583500f; + TrackCoor3[1] = -121.879615f; + track_coordinates.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.586307f; + TrackCoor4[1] = -121.874582f; + track_coordinates.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 36.588670f; + TrackCoor5[1] = -121.877928f; + track_coordinates.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 36.591124f; + TrackCoor6[1] = -121.880074f; + track_coordinates.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 36.592827f; + TrackCoor7[1] = -121.877149f; + track_coordinates.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 36.594051f; + TrackCoor8[1] = -121.877452f; + track_coordinates.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 36.594245f; + TrackCoor9[1] = -121.876477f; + track_coordinates.add(TrackCoor9); + Float[] TrackCoor10 = new Float [2]; + TrackCoor10[0] = 36.595230f; + TrackCoor10[1] = -121.877537f; + track_coordinates.add(TrackCoor10); +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + + + +// System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); +// for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + for(int idx = 0; idx < 10; idx++) + { + System.out.println("Sending ESPDU packet " + idx + " to " + destinationIp.toString()); + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + Float lat = track_coordinates.get(idx)[0]; + Float lon = track_coordinates.get(idx)[1]; + +// double direction = Math.pow((double)(-1.0), (double)(idx)); +// lon = lon + (direction * 0.00006); + + +// System.out.println(lon); + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon: " + lat + ", " + lon); + System.out.println("DIS coord: " + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) +// packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate +// socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.pdf new file mode 100644 index 0000000000000000000000000000000000000000..f4d55e584bcfee4ced1059c9e79e597e1a13179a Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Landas_OpenDisEspduSender.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..c1686084a94f5ef9dbe745bb6dfc4f3466f27fd3 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisEspduSender.java @@ -0,0 +1,365 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + private static final ArrayList <Float[]> track = new ArrayList<>(); + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + //double lat = 36.595517; + //double lon = -121.877000; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.59135f; + TrackCoor1[1] = -121.88051f; + track.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.59487f; + TrackCoor2[1] = -121.86739f; + track.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.63259f; + TrackCoor3[1] = -121.66926f; + track.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.64481f; + TrackCoor4[1] = -121.61162f; + track.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 35.64239f; + TrackCoor5[1] = -120.68503f; + track.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 35.61577f; + TrackCoor6[1] = -119.65283f; + track.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 34.76589f; + TrackCoor7[1] = -118.79854f; + track.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 34.77651f; + TrackCoor8[1] = -118.17049f; + track.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 34.5806f; + TrackCoor9[1] = -118.1334f; + track.add(TrackCoor9); + +// System.out.println("********" + String.valueOf(track_coordinates[0]) ); +// System.out.println("********" + track_coordinates.get(5)[1]); + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + Float lat = track.get(idx)[0]; + Float lon = track.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon:" + lat + ", " + lon); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu firePdu = new FirePdu(); + byte[] fireArray = firePdu.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator iteratorBroadcastAddresses = broadcastAddresses.iterator(); + while(iteratorBroadcastAddresses.hasNext()) + { + InetAddress broadcastAddress = (InetAddress)iteratorBroadcastAddresses.next(); + System.out.println("Sending broadcast datagram packet to " + broadcastAddress); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcastAddress, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcastAddress, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; // skip to next iterator value + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisPduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisPduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..cfdc2f89c285fb5bad2abe4cfa3ee56768c346b2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/OpenDisPduSender.java @@ -0,0 +1,184 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disenum.*; + +/** + * This is an example that sends many/most types of PDUs. Useful for testing standards + * compliance or getting a full set of PDUs. It also writes the generated PDUs to + * an XML file. + * + * @author DMcG + * @version $Id:$ + */ +public class OpenDisPduSender { + + public static final int PORT = 3000; + public static final String MULTICAST_ADDRESS = "239.1.2.3"; + private int port; + InetAddress multicastAddress; + + public OpenDisPduSender(int port, String multicast) + { + try { + this.port = port; + multicastAddress = InetAddress.getByName(multicast); + if (!multicastAddress.isMulticastAddress()) { + System.out.println("Not a multicast address: " + multicast); + } + } + catch (UnknownHostException e) { + System.out.println("Unable to open socket: " + e); + } + } + + public void run() { + try { + List<Pdu> generatedPdus = new ArrayList<>(); + + // Loop through all the enumerated PDU types, create a PDU for each type, + // and add that PDU to a list. + for (PduType pdu : PduType.values()) { + Pdu aPdu = null; + + switch (pdu) { + case ENTITY_STATE: + // TODO continue to add unit tests + EntityStatePdu entityStatePdu = new EntityStatePdu(); + Marking espduMarking = new Marking(); + espduMarking.setCharactersString("Testing 123"); + // TODO libary should warn if > 11 characters + entityStatePdu.setMarking(espduMarking); + EntityID espduEntityID = new EntityID(); + espduEntityID.setSite(1); + espduEntityID.setApplication(2); + espduEntityID.setEntity(3); + entityStatePdu.setEntityID(espduEntityID); + // TODO consider adding utility methods to Open-DIS + aPdu = entityStatePdu; + break; + + case COMMENT: + aPdu = new CommentPdu(); + break; + + case FIRE: + aPdu = new FirePdu(); + break; + + case DETONATION: + aPdu = new DetonationPdu(); + break; + + case COLLISION: + aPdu = new CollisionPdu(); + break; + + case SERVICE_REQUEST: + aPdu = new ServiceRequestPdu(); + break; + + case RESUPPLY_OFFER: + aPdu = new ResupplyOfferPdu(); + break; + + case RESUPPLY_RECEIVED: + aPdu = new ResupplyReceivedPdu(); + break; + + case RESUPPLY_CANCEL: + aPdu = new ResupplyCancelPdu(); + break; + + case REPAIR_COMPLETE: + aPdu = new RepairCompletePdu(); + break; + + case REPAIR_RESPONSE: + aPdu = new RepairResponsePdu(); + break; + + case CREATE_ENTITY: + aPdu = new CreateEntityPdu(); + break; + + case REMOVE_ENTITY: + aPdu = new RemoveEntityPdu(); + break; + + case START_RESUME: + aPdu = new StartResumePdu(); + break; + + case STOP_FREEZE: + aPdu = new StopFreezePdu(); + break; + + case ACKNOWLEDGE: + aPdu = new AcknowledgePdu(); + break; + + case ACTION_REQUEST: + aPdu = new ActionRequestPdu(); + break; + + default: + System.out.print("PDU of type " + pdu + " not supported, created or sent "); + System.out.println(); + } + + if (aPdu != null) { + generatedPdus.add(aPdu); + } + } + + // Sort the created PDUs by class name + Collections.sort(generatedPdus, new edu.nps.moves.examples.ClassNameComparator()); + + // Send the PDUs we created + InetAddress localMulticastAddress = InetAddress.getByName(MULTICAST_ADDRESS); + MulticastSocket socket = new MulticastSocket(PORT); + socket.joinGroup(localMulticastAddress); + + for (int idx = 0; idx < generatedPdus.size(); idx++) { + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + byte[] buffer; + + Pdu aPdu = generatedPdus.get(idx); + aPdu.marshal(dos); + + buffer = baos.toByteArray(); + DatagramPacket packet = new DatagramPacket(buffer, buffer.length, localMulticastAddress, PORT); + socket.send(packet); + System.out.println("Sent PDU of type " + aPdu.getClass().getName()); + } + + // write the PDUs out to an XML file. + //PduContainer container = new PduContainer(); + //container.setPdus(generatedPdus); + //container.marshallToXml("examplePdus.xml"); + } + catch (IOException e) { + System.out.println(e); + } + } + + public static void main(String args[]) { + if (args.length == 2) { + OpenDisPduSender sender = new OpenDisPduSender(Integer.parseInt(args[0]), args[1]); + sender.run(); + } else { + System.out.println("Usage: OpenDisPduSender <port> <multicast group>"); + System.out.println("Default: OpenDisPduSender " + PORT + " " + MULTICAST_ADDRESS); + OpenDisPduSender sender = new OpenDisPduSender(PORT, MULTICAST_ADDRESS); + sender.run(); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f9a452de16bbe96b061f1479350f89ea148ca2e2 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/README.md @@ -0,0 +1,24 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [ ] Copy README.md and create YournameREADME.md documentation file... + +1. [ ] Plan a track of interest, described in YournameREADME.md documentation file... + +1. [ ] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [ ] Modify your example file to produce track PDUs (and be cool) + +1. [ ] Generate PDUs... + +1. [ ] Test PDU reading using Wireshark... + +1. [ ] Record PDU file using X3D-Edit... + +1. [ ] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_HW3_Screenshots.pdf b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_HW3_Screenshots.pdf new file mode 100644 index 0000000000000000000000000000000000000000..49d03e35f7783db967736bbb1ed2072a60c1aba6 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_HW3_Screenshots.pdf differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java new file mode 100644 index 0000000000000000000000000000000000000000..d817fda11b431016fd83db822f9608b6f5d9054b --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_OpenDisEspduSender1.java @@ -0,0 +1,299 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Sasala_OpenDisEspduSender1 +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double radians = 0; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + radians = (radians + (Math.PI/6)) % (2*Math.PI); + + Vector3Double location = espdu.getEntityLocation(); + location.setX(Math.cos(radians)*1000); + location.setY(Math.sin(radians)*1000); + location.setZ(250); + + // Optionally, we can do some rotation of the entity + + Orientation orientation = espdu.getEntityOrientation(); + orientation.setTheta((float)(radians + (Math.PI/2))%(float)(Math.PI *2)); + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + location = espdu.getEntityLocation(); + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + System.out.println(" Orientation: " + orientation.getTheta()); + //System.out.println(" Location (lat/lon/alt): [" + lat + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_README.md new file mode 100644 index 0000000000000000000000000000000000000000..9e62214da8776261af2c6cbc52a43e50e31b8041 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Sasala_README.md @@ -0,0 +1,29 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +2. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +3. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +4. [x] Copy README.md and create YournameREADME.md documentation file... + +5. [x] Plan a track of interest - entity travels in a circle and changes heading(orientation) correspondingly + +6. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +7. [x] Modify your example file to produce track PDUs (and be cool) + +8. [x] Generate PDUs... + +9. [x] Test PDU reading using Wireshark...example below (see also screenshot file) + +835 46.316530 172.20.155.227 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) +799 43.208823 172.20.155.227 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) +722 40.094776 172.20.155.227 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) +631 37.026221 172.20.155.227 172.20.159.255 DIS 186 PDUType: 1 Entity State, Platform, Land, (1:1:2) + +10. [x] Record PDU file using X3D-Edit... + +11. [x] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..6a1cfd0f6eb38846c6b6b1d04f049372db73f631 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_OpenDisEspduSender.java @@ -0,0 +1,371 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +// package edu.nps.moves.examples; // copy example from OpenDIS distribution, modify to serve as template + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * Creates and sends ESPDUs in IEEE binary format. + * + * @author DMcG + */ +public class Tackett_Assignment3_OpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 10; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + + private static final ArrayList <Float[]> track_coordinates = new ArrayList<>(); + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // Lat/Lon coordinates +// double lat = 36.616366; +// double lon = -121.913065; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(225); // USA + entityType.setDomain((short)1); // Land (vs air, surface, subsurface, space) + entityType.setCategory((short)1); // Tank + entityType.setSubcategory((short)1); // M1 Abrams + entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + Float[] TrackCoor1 = new Float [2]; + TrackCoor1[0] = 36.585657f; + TrackCoor1[1] = -121.879920f; + track_coordinates.add(TrackCoor1); + Float[] TrackCoor2 = new Float [2]; + TrackCoor2[0] = 36.584853f; + TrackCoor2[1] = -121.880024f; + track_coordinates.add(TrackCoor2); + Float[] TrackCoor3 = new Float [2]; + TrackCoor3[0] = 36.583500f; + TrackCoor3[1] = -121.879615f; + track_coordinates.add(TrackCoor3); + Float[] TrackCoor4 = new Float [2]; + TrackCoor4[0] = 36.586307f; + TrackCoor4[1] = -121.874582f; + track_coordinates.add(TrackCoor4); + Float[] TrackCoor5 = new Float [2]; + TrackCoor5[0] = 36.588670f; + TrackCoor5[1] = -121.877928f; + track_coordinates.add(TrackCoor5); + Float[] TrackCoor6 = new Float [2]; + TrackCoor6[0] = 36.591124f; + TrackCoor6[1] = -121.880074f; + track_coordinates.add(TrackCoor6); + Float[] TrackCoor7 = new Float [2]; + TrackCoor7[0] = 36.592827f; + TrackCoor7[1] = -121.877149f; + track_coordinates.add(TrackCoor7); + Float[] TrackCoor8 = new Float [2]; + TrackCoor8[0] = 36.594051f; + TrackCoor8[1] = -121.877452f; + track_coordinates.add(TrackCoor8); + Float[] TrackCoor9 = new Float [2]; + TrackCoor9[0] = 36.594245f; + TrackCoor9[1] = -121.876477f; + track_coordinates.add(TrackCoor9); + Float[] TrackCoor10 = new Float [2]; + TrackCoor10[0] = 36.595230f; + TrackCoor10[1] = -121.877537f; + track_coordinates.add(TrackCoor10); + + //System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + System.out.println("Sending espdu packet" + idx + " to " + destinationIp.toString()); + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + +// double direction = Math.pow((double)(-1.0), (double)(idx)); +// lon = lon + (direction * 0.00006); +// System.out.println(lon); + + Float lat = track_coordinates.get(idx)[0]; + Float lon = track_coordinates.get(idx)[1]; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, 1.0); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon:" + lat + ", " + lon); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) +// packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate +// socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README new file mode 100644 index 0000000000000000000000000000000000000000..0efea04a6c9b411a6556182e6cbc40357b89370a --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README @@ -0,0 +1,36 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + + Track of interest is a sample from a run route I did recently. + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + + IP address for my machine is 172.20.148.166 + + References: capturing packets using Wireshark in pcapng format + + Wireshark Users Guide, 5.2. Open capture files + https://www.wireshark.org/docs/wsug_html_chunked/ChIOOpenSection.html + + Wireshark Users Guide, 5.3. Saving captured packets + https://www.wireshark.org/docs/wsug_html_chunked/ChIOSaveSection.html + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.html b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.html new file mode 100644 index 0000000000000000000000000000000000000000..466feff569a72d4a83bbad9b443a6054fa3d69a9 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.html @@ -0,0 +1,28 @@ +<!DOCTYPE html> +<html> +<head> +<meta http-equiv="content-type" content="text/html; charset=UTF-8"> +<title>Tackett_Assignment3_README</title> +<style type="text/css">/*...*/</style> +</head> +<body> +<h2>Homework Assignment 3 Checklist</h2> +<ol> + <li><p>[x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads</p></li> + <li><p>[x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java</p></li> + <li><p>[x] Otherwise just inspect files of interest from <a href="https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples">edu.nps.moves.examples</a></p></li> + <li><p>[x] Copy README.md and create YournameREADME.md documentation file...</p></li> + <li><p>[x] Plan a track of interest, described in YournameREADME.md documentation file...</p> + <pre><code>Track of interest is a sample from a run route I did recently. +</code></pre></li> + <li><p>[x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java</p></li> + <li><p>[x] Modify your example file to produce track PDUs (and be cool)</p></li> + <li><p>[x] Generate PDUs...</p></li> + <li><p>[x] Test PDU reading using Wireshark...</p> + <pre><code>IP address for my machine is 172.20.148.166 +</code></pre></li> + <li><p>[x] Record PDU file using X3D-Edit...</p></li> + <li><p>[x] Playback PDU file using X3D-Edit...</p></li> +</ol> +</body> +</html> \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.md new file mode 100644 index 0000000000000000000000000000000000000000..ec5cbee9d81ee3b426d62ab3014fa17ff92a4a9f --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Assignment3_README.md @@ -0,0 +1,28 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + + Track of interest is a sample from a run route I did recently. + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + + IP address for my machine is 172.20.148.166 + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Wireshark.pcapng b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Wireshark.pcapng new file mode 100644 index 0000000000000000000000000000000000000000..6e0277a4267aa4f983d0b68438c1198e7674d99e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_Wireshark.pcapng differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..97e028dbc8fc06aed0c49550ca39908bbf202d0e Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..2e233e8f442f5a5453dc49b6ef83c3dc72deead9 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/Tackett_dispackets.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java new file mode 100644 index 0000000000000000000000000000000000000000..f828af4fb43b47c1ef4af03fcce54ae7926fb289 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOpenDisEspduSender.java @@ -0,0 +1,332 @@ +package MV3500Cohort2018JanuaryMarch.homework3; + +import java.io.*; +import java.net.*; +import java.util.*; + +import edu.nps.moves.dis.*; +import edu.nps.moves.disutil.CoordinateConversions; +import edu.nps.moves.disutil.DisTime; + +/** + * MV3500 + * + * Creates and sends ESPDUs in IEEE binary format. + * + * @author Douglas Yamashita de Moura + * @version 20180306 + * + */ + +public class YamashitaDeMouraOpenDisEspduSender +{ + public static final int NUMBER_TO_SEND = 5000; + + public enum NetworkMode{UNICAST, MULTICAST, BROADCAST}; + + /** Default multicast group address we send on */ + public static final String DEFAULT_MULTICAST_GROUP="239.1.2.3"; + + /** Default port we send on */ + public static final int DIS_DESTINATION_PORT = 3000; + +/** Possible system properties, passed in via -Dattr=val + * networkMode: unicast, broadcast, multicast + * destinationIp: where to send the packet. If in multicast mode, this can be multicast. + * To determine broadcast destination IP, use an online broadcast address + * calculator, for example http://www.remotemonitoringsystems.ca/broadcast.php + * If in multicast mode, a join() will be done on the multicast address. + * port: port used for both source and destination. + * @param args + */ +public static void main(String args[]) +{ + /** an entity state pdu */ + EntityStatePdu espdu = new EntityStatePdu(); + MulticastSocket socket = null; // must be initialized, even if null + DisTime disTime = DisTime.getInstance(); // TODO explain + int alternator = -1; + + // ICBM coordinates for my office + double lat = 36.595517; + double lon = -121.877000; + double hei = 0.0; + + // Default settings. These are used if no system properties are set. + // If system properties are passed in, these are over ridden. + int port = DIS_DESTINATION_PORT; + NetworkMode mode = NetworkMode.BROADCAST; + InetAddress destinationIp = null; // must be initialized, even if null + + try + { + destinationIp = InetAddress.getByName(DEFAULT_MULTICAST_GROUP); + } + catch(UnknownHostException e) + { + System.out.println(e + " Cannot create multicast address"); + System.exit(0); + } + + // All system properties, passed in on the command line via -Dattribute=value + Properties systemProperties = System.getProperties(); + + // IP address we send to + String destinationIpString = systemProperties.getProperty("destinationIp"); + + // Port we send to, and local port we open the socket on + String portString = systemProperties.getProperty("port"); + + // Network mode: unicast, multicast, broadcast + String networkModeString = systemProperties.getProperty("networkMode"); // unicast or multicast or broadcast + + // Set up a socket to send information + try + { + // Port we send to + if(portString != null) + port = Integer.parseInt(portString); + + socket = new MulticastSocket(port); + + // Where we send packets to, the destination IP address + if(destinationIpString != null) + { + destinationIp = InetAddress.getByName(destinationIpString); + } + + // Type of transport: unicast, broadcast, or multicast + // TODO convert to String constants + if(networkModeString != null) + { + if(networkModeString.equalsIgnoreCase("unicast")) + mode = NetworkMode.UNICAST; + else if(networkModeString.equalsIgnoreCase("broadcast")) + mode = NetworkMode.BROADCAST; + else if(networkModeString.equalsIgnoreCase("multicast")) + { + mode = NetworkMode.MULTICAST; + if(!destinationIp.isMulticastAddress()) + { + throw new RuntimeException("Sending to multicast address, but destination address " + destinationIp.toString() + "is not multicast"); + } + + socket.joinGroup(destinationIp); + } + } // end networkModeString + } + catch(IOException | RuntimeException e) + { + System.out.println("Unable to initialize networking. Exiting."); + System.out.println(e); + System.exit(-1); + } + + // Initialize values in the Entity State PDU object. The exercise ID is + // a way to differentiate between different virtual worlds on one network. + // Note that some values (such as the PDU type and PDU family) are set + // automatically when you create the ESPDU. + espdu.setExerciseID((short)1); + + // The EID is the unique identifier for objects in the world. This + // EID should match up with the ID for the object specified in the + // VMRL/x3d/virtual world. + EntityID entityID = espdu.getEntityID(); + entityID.setSite(1); // 0 is apparently not a valid site number, per the spec + entityID.setApplication(1); + entityID.setEntity(2); + + // Set the entity type. SISO has a big list of enumerations, so that by + // specifying various numbers we can say this is an M1A2 American tank, + // the USS Enterprise, and so on. We'll make this a tank. There is a + // separate project elsehwhere in this project that implements DIS + // enumerations in C++ and Java, but to keep things simple we just use + // numbers here. + EntityType entityType = espdu.getEntityType(); + entityType.setEntityKind((short)1); // Platform (vs lifeform, munition, sensor, etc.) + entityType.setCountry(29); // Brazil + entityType.setDomain((short)2); // Air (vs land, surface, subsurface, space) + entityType.setCategory((short)2); // Attack/Strike + entityType.setSubcategory((short)1); // Embraer Super Tucano + //entityType.setSpec((short)3); // M1A2 Abrams + + + Set<InetAddress> broadcastAddresses; + // Loop through sending N ESPDUs + try + { + System.out.println("Sending " + NUMBER_TO_SEND + " ESPDU packets to " + destinationIp.toString()); + for(int idx = 0; idx < NUMBER_TO_SEND; idx++) + { + // DIS time is a pain in the ass. DIS time units are 2^31-1 units per + // hour, and time is set to DIS time units from the top of the hour. + // This means that if you start sending just before the top of the hour + // the time units can roll over to zero as you are sending. The receivers + // (escpecially homegrown ones) are often not able to detect rollover + // and may start discarding packets as dupes or out of order. We use + // an NPS timestamp here, hundredths of a second since the start of the + // year. The DIS standard for time is often ignored in the wild; I've seen + // people use Unix time (seconds since 1970) and more. Or you can + // just stuff idx into the timestamp field to get something that is monotonically + // increasing. + + // Note that timestamp is used to detect duplicate and out of order packets. + // That means if you DON'T change the timestamp, many implementations will simply + // discard subsequent packets that have an identical timestamp. Also, if they + // receive a PDU with an timestamp lower than the last one they received, they + // may discard it as an earlier, out-of-order PDU. So it is a good idea to + // update the timestamp on ALL packets sent. + + + // An alterative approach: actually follow the standard. It's a crazy concept, + // but it might just work. + int timestamp = disTime.getDisAbsoluteTimestamp(); + espdu.setTimestamp(timestamp); + + // Set the position of the entity in the world. DIS uses a cartesian + // coordinate system with the origin at the center of the earth, the x + // axis out at the equator and prime meridian, y out at the equator and + // 90 deg east, and z up and out the north pole. To place an object on + // the earth's surface you also need a model for the shape of the earth + // (it's not a sphere.) All the fancy math necessary to do this is in + // the SEDRIS SRM package. There are also some one-off formulas for + // doing conversions from, for example, lat/lon/altitude to DIS coordinates. + // Here we use those one-off formulas. + + // Modify the position of the object. This will send the object a little + // due east by adding some to the longitude every iteration. Since we + // are on the Pacific coast, this sends the object east. Assume we are + // at zero altitude. In other worlds you'd use DTED to determine the + // local ground altitude at that lat/lon, or you'd just use ground clamping. + // The x and y values will change, but the z value should not. + + //lon = lon + (double)((double)idx / 100000.0); + //System.out.println("lla=" + lat + "," + lon + ", 0.0"); + + double direction = Math.pow((double)(-1.0), (double)(idx)); + lon = lon + (direction * 0.00006); + //System.out.println(lon); + + // Rate of climb (RoC) (up to 10 m/s) + double roc = Math.floor(Math.random()*Math.floor(10)); + hei = hei + roc; + + double disCoordinates[] = CoordinateConversions.getXYZfromLatLonDegrees(lat, lon, hei); + Vector3Double location = espdu.getEntityLocation(); + location.setX(disCoordinates[0]); + location.setY(disCoordinates[1]); + location.setZ(disCoordinates[2]); + System.out.println("lat, lon, hei:" + lat + ", " + lon + ", " + hei); + System.out.println("DIS coord:" + disCoordinates[0] + ", " + disCoordinates[1] + ", " + disCoordinates[2]); + + // Optionally, we can do some rotation of the entity + /* + Orientation orientation = espdu.getEntityOrientation(); + float psi = orientation.getPsi(); + psi = psi + idx; + orientation.setPsi(psi); + orientation.setTheta((float)(orientation.getTheta() + idx /2.0)); + */ + + // You can set other ESPDU values here, such as the velocity, acceleration, + // and so on. + + // Marshal out the espdu object to a byte array, then send a datagram + // packet with that data in it. + ByteArrayOutputStream baos = new ByteArrayOutputStream(); + DataOutputStream dos = new DataOutputStream(baos); + espdu.marshal(dos); + + FirePdu fire = new FirePdu(); + byte[] fireArray = fire.marshal(); + + // The byte array here is the packet in DIS format. We put that into a + // datagram and send it. + byte[] data = baos.toByteArray(); + + broadcastAddresses = getBroadcastAddresses(); + Iterator it = broadcastAddresses.iterator(); + while(it.hasNext()) + { + InetAddress broadcast = (InetAddress)it.next(); + System.out.println("Sending broadcast datagram packet to " + broadcast + "\n"); + DatagramPacket packet = new DatagramPacket(data, data.length, broadcast, 3000); + socket.send(packet); + // TODO experiment with these! 8) + packet = new DatagramPacket(fireArray, fireArray.length, broadcast, 3000); // alternate + socket.send(packet); + } + + // Send every 1 sec. Otherwise this will be all over in a fraction of a second. + Thread.sleep(3000); + + location = espdu.getEntityLocation(); + + System.out.println("Espdu #" + idx + " EID=[" + entityID.getSite() + "," + entityID.getApplication() + "," + entityID.getEntity() + "]"); + System.out.println(" DIS coordinates location=[" + location.getX() + "," + location.getY() + "," + location.getZ() + "]"); + double c[] = {location.getX(), location.getY(), location.getZ()}; + double lla[] = CoordinateConversions.xyzToLatLonDegrees(c); +// System.out.println(" Location (lat/lon/alt): [" + lla[0] + ", " + lla[1] + ", " + lla[2] + "]"); + + } + } + catch(IOException | InterruptedException e) + { + System.out.println(e); + } + +} + + /** + * A number of sites get all snippy about using 255.255.255.255 for a broadcast + * address; it trips their security software and they kick you off their + * network. (Comcast, NPS.) This determines the broadcast address for all + * connected interfaces, based on the IP and subnet mask. If you have + * a dual-homed host it will return a broadcast address for both. If you have + * some VMs running on your host this will pick up the addresses for those + * as well--eg running VMWare on your laptop with a local IP this will + * also pick up a 192.168 address assigned to the VM by the host OS. + * + * @return set of all broadcast addresses + */ + public static Set<InetAddress> getBroadcastAddresses() + { + Set<InetAddress> broadcastAddresses = new HashSet<>(); + Enumeration interfaces; + + try + { + interfaces = NetworkInterface.getNetworkInterfaces(); + + while(interfaces.hasMoreElements()) + { + NetworkInterface anInterface = (NetworkInterface)interfaces.nextElement(); + + if(anInterface.isUp()) + { + Iterator it = anInterface.getInterfaceAddresses().iterator(); + while(it.hasNext()) + { + InterfaceAddress anAddress = (InterfaceAddress)it.next(); + if((anAddress == null || anAddress.getAddress().isLinkLocalAddress())) + continue; + + //System.out.println("Getting broadcast address for " + anAddress); + InetAddress broadcastAddress = anAddress.getBroadcast(); + if(broadcastAddress != null) + broadcastAddresses.add(broadcastAddress); + } + } + } + + } + catch(SocketException e) + { + e.printStackTrace(); + System.out.println(e); + } + + return broadcastAddresses; + } + +} diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin new file mode 100644 index 0000000000000000000000000000000000000000..4c7ab29a08cb48b4993a50104431ee0ac4e009db Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin.disbinidx b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin.disbinidx new file mode 100644 index 0000000000000000000000000000000000000000..f0c73ee32e9149948e5d4d2534affdd579967415 Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputDispackets.disbin.disbinidx differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputNetBeansWireshark.PNG b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputNetBeansWireshark.PNG new file mode 100644 index 0000000000000000000000000000000000000000..b1b81965d57beb5341ad244d5e506ad0ec8a309f Binary files /dev/null and b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraOutputNetBeansWireshark.PNG differ diff --git a/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraREADME.md b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraREADME.md new file mode 100644 index 0000000000000000000000000000000000000000..7f0b7fc6bcf25584189a881b8ad70d45b53922ab --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JanuaryMarch/homework3/YamashitaDeMouraREADME.md @@ -0,0 +1,31 @@ +## Homework Assignment 3 Checklist + +1. [x] Add X3D-Edit as Netbeans Plugin from https://savage.nps.edu/X3D-Edit/#Downloads + +1. [x] Optional: checkout Open-DIS-Java library source from https://github.com/open-dis/open-dis-java + +1. [x] Otherwise just inspect files of interest from + [edu.nps.moves.examples](https://github.com/open-dis/open-dis-java/tree/master/src/main/java/edu/nps/moves/examples) + +1. [x] Copy README.md and create YournameREADME.md documentation file... + +1. [x] Plan a track of interest, described in YournameREADME.md documentation file... + +1. [x] Copy, then Refactor/Rename example file OpenDisEspduSender.java or OpenDisPduSender.java as YourNameSomething.java + +1. [x] Modify your example file to produce track PDUs (and be cool) + +1. [x] Generate PDUs... + +1. [x] Test PDU reading using Wireshark... + +1. [x] Record PDU file using X3D-Edit... + +1. [x] Playback PDU file using X3D-Edit... + +Track of interest: +- Brazilian Attack/Strike Embraer Super Tucano + +Notes: +- The height of the aircraft is increasing on RoC (Rate of Climb) up to 10 m/s +- Wireshark correctly recognized the entity type. However, X3D recognized incorrectly the category and sub-category of the entity type. \ No newline at end of file diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/homework1/CainAssignment1.java b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/CainAssignment1.java new file mode 100644 index 0000000000000000000000000000000000000000..5e0287e9246c95fab462d5e0f38bd1ef16e4dd37 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/CainAssignment1.java @@ -0,0 +1,68 @@ +package MV3500Cohort2018JulySeptember.homework1; + +import java.io.*; +import java.net.*; + +/** + * changed telnet # from 2317 to 2318. This won't affect the protocol handshake + * as long as client inputs the correct telnet #. + * + * telnet localhost 2318 + * + * ask for the ip address of the server + * <code>telnet ipOfServersLaptop 2318</code> + */ +public class CainAssignment1 { + + public static void main(String[] args) { + try { + int popularityCount = 0; // state + + ServerSocket serverSocket = new ServerSocket(2318); // server decides here what port to listen on. + // of interest: often client doesn't care what port it uses locally when connecting to that server port. + + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while (true) { + Socket clientConnection = serverSocket.accept(); // blocks! then proceeds once a connection is "accept"ed + + /** + * changed connectionCount to popularityCount + */ + popularityCount++; + + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("This client response was written by server CainAssignment1"); // to remote client + System.out.println("This server response was written by server CainAssignment1"); // to server console + + ps.println("You were connection #" + popularityCount + ", by my count"); + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); // remember the prior question, why are 2 ports different? + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) note IPv6 + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + System.out.println("you'er server is blowing up! Now serving #" + popularityCount); // report progress + + ps.flush(); + clientConnection.close(); + } + } catch (Exception e) { + /** + * added to the println for fun + */ + System.out.println("you got all sorts of problems with your networking: " + e); + } + } +} diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FriscoTcpClient.java b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FriscoTcpClient.java new file mode 100644 index 0000000000000000000000000000000000000000..bead2df05984b8fca73983b3da6fed1ce21cde45 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FriscoTcpClient.java @@ -0,0 +1,72 @@ +package MV3500Cohort2018JulySeptember.homework1; + +import java.io.BufferedReader; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.OutputStream; +import java.io.PrintStream; +import java.net.Socket; + + +import java.io.*; +import java.net.*; +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ + +/** + * + * @author djfrisco + */ +public class FriscoTcpClient { + + public static void main(String[] args) + { + try + { + System.out.println("creating socket"); + + // We request an IP to connect to ("localhost") and + // port number at that IP (2317). This establishes + // a connection to that IP in the form of the Socket + // object; the server uses a ServerSocket to wait for + // connections. + Socket socket = new Socket("localhost", 2317); + + // Read the single line written by the server. We'd + // do things a bit differently if many lines to be read + // from the server, instead of one only. + InputStream is = socket.getInputStream(); + InputStreamReader isr = new InputStreamReader(is); + BufferedReader br = new BufferedReader(isr); + + String serverMessage = br.readLine(); + System.out.println("1 The message the server sent was " + serverMessage); + + // Outgoing Messages + OutputStream os = socket.getOutputStream(); + PrintStream ps = new PrintStream(os); + ps.println("bbb report: X, Y, X " + System.currentTimeMillis()); + + serverMessage = br.readLine(); + System.out.println("2 The message the server sent was " + serverMessage); + + //os = socket.getOutputStream(); + // ps = new PrintStream(os); + ps.println("Final message from client " + System.currentTimeMillis()); + serverMessage = br.readLine(); + System.out.println("3 The message the server sent was " + serverMessage); + + + } + catch(Exception e) + { + System.out.println(e); + System.out.println("Problem with client"); + } + + } +} + diff --git a/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FurrAssignment2.java b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FurrAssignment2.java new file mode 100644 index 0000000000000000000000000000000000000000..e7f6739d01197a2a85cefb41f62a5f7a71e77672 --- /dev/null +++ b/deliverables/src/MV3500Cohort2018JulySeptember/homework1/FurrAssignment2.java @@ -0,0 +1,92 @@ +package MV3500Cohort2018JulySeptember.homework1; + +import java.io.*; +import java.net.*; + +/** + * Very slightly more complex than example1. The only thing this does + * differently is introduce a loop into the response, so you don't + * have to restart the program after one response. Also, it prints + * out the socket pair the server sees. Run the program via telnet + * several times and compare the socket pairs. + * + * telnet localhost 2317 + * + * If you're sophisticated you can contact the instructor's computer + * while running this program. + * + * telnet <ipOfServersLaptop> 2317 + * + * And have him display the socket pairs he got. + * @author mcgredo + */ +public class FurrAssignment2 +{ + + public static void main(String[] args) + { + try + { + // ServerSocket waits for a connection from a client. + // Notice that it is outside the loop; ServerSocket + // needs to be made only once. + + int connectionCount = 0; // state + for(int i=2317; i<10; i++){ + ServerSocket serverSocket = new ServerSocket(i); + System.out.println("server established for port #" +i); + } + + // Loop, infinitely, waiting for client connections. + // Stop the program somewhere else. + while(true) + { + Socket clientConnection = serverSocket.accept(); // blocks! then proceeds once a connection is "accept"ed + + connectionCount++; // got another one! + + OutputStream os = clientConnection.getOutputStream(); + PrintStream ps = new PrintStream(os); + + ps.println("This client response was written by server TcpExample2"); // to remote client + System.out.println("This server response was written by server TcpExample2"); // to server console + + // Print some information locally about the Socket + // connection. This includes the port and IP numbers + // on both sides (the socket pair.) + + InetAddress localAddress = clientConnection.getLocalAddress(); + InetAddress remoteAddress = clientConnection.getInetAddress(); + + int localPort = clientConnection.getLocalPort(); + int remotePort = clientConnection.getPort(); + + // My socket pair connection looks like this, to localhost: + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54876 )) + // Socket pair: (( /0:0:0:0:0:0:0:1, 2317 ), ( /0:0:0:0:0:0:0:1, 54881 )) + // + // Why is the first IP/port the same, while the second set has + // different ports? + + + System.out.println("Socket pair: (( " + localAddress.toString() + ", " + localPort + " ), ( " + + remoteAddress.toString() + ", " + remotePort + " ))"); + + System.out.println("got another connection, #" + connectionCount); // report progress + + // Notice the use of flush() and close(). Without + // the close() to Socket object may stay open for + // a while after the client has stopped needing this + // connection. Close() explicitly ends the connection. + ps.flush(); + clientConnection.close(); + } + } + catch(Exception e) + { + System.out.println("problem with networking: " + e); + } + + } + +}